简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM