简体   繁体   中英

How do I slice an OrderedDict?

I tried slicing an OrderedDict like this:

for key in some_dict[:10]:

But I get a TypeError saying "unhashable type: 'slice'". How do I get this dictionary's first 10 key-value pairs?

Try converting the OrderedDict into something that is sliceable:

list_dict = list(some_dict.items())

for i in list_dict[:10]:
  # do something

Now each key-value pair is a two-item tuple. (index 0 is key, index 1 is value)

An OrderedDict is only designed to maintain order, not to provide efficient lookup by position in that order. (Internally, they maintain order with a doubly-linked list.) OrderedDicts cannot provide efficient general-case slicing, so they don't implement slicing.

For your use case, you can instead use itertools to stop the loop after 10 elements:

import itertools

for key in itertools.islice(your_odict, 0, 10):
    ...

or

for key, value in itertools.islice(your_odict.items(), 0, 10):
    ...

Internally, islice will just stop fetching items from the underlying OrderedDict iterator once it reaches the 10th item. Note that while you can tell islice to use a step value, or a nonzero start value, it cannot do so efficiently - it will have to fetch and discard all the values you want to skip to get to the ones you're interested in.

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