python return first n key values pairs from dictionary code example
Example 1: python return first n key values pairs from dictionary
{key: dictionary[key] for key in list(dictionary)[:number_keys]}
dictionary = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
{key: dictionary[key] for key in list(dictionary)[:2]}
--> {'a': 3, 'b': 2}
dictionary = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
{key: dictionary[key] for key in list(dictionary)[2:5]}
--> {'c': 3, 'd': 4, 'e': 5}
Example 2: get n items from dictionary python
list(islice(d.iteritems(), n))
'Update for Python 3.6
list(islice(d.items(), n))