How to iterate over the first n elements of a dictionary in python?

Viewed 2330

Simple question here:

If I try to slice my dictionary (parsed from an xml file) in python, I will get a TypeError: unhashable type: 'slice'

for section in my_dict[:3] ['CATEGORY']['SUBCATEGORY']:

it looks like it doesn't work for dictionaries, do they have a specific method? Or is it because of the 2 other arguments coming right after that are misinterpreted?

1 Answers

You can use itertools.islice:

from itertools import islice

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for item in islice(d, 3):  # use islice(d.items(), 3) to iterate over key/value pairs
    print(item)

Output:

a
b
c
Related