1# Basic syntax:
2{key: dictionary[key] for key in list(dictionary)[:number_keys]}
3
4# Note, number_keys is the number of key:value pairs to return from the
5# dictionary, not including the number_keys # itself
6# Note, Python is 0-indexed
7# Note, this formula be adapted to return any slice of keys from the
8# dictionary following similar slicing rules as for lists
9
10# Example usage 1:
11dictionary = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
12{key: dictionary[key] for key in list(dictionary)[:2]}
13--> {'a': 3, 'b': 2} # The 0th to 1st key:value pairs
14
15# Example usage 2:
16dictionary = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
17{key: dictionary[key] for key in list(dictionary)[2:5]}
18--> {'c': 3, 'd': 4, 'e': 5} # The 2nd to 4th key:value pairs
1list(islice(d.iteritems(), n))
2'Update for Python 3.6
3list(islice(d.items(), n))