0

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?

2 Answers2

2

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)

Stick-Figure
  • 101
  • 7
2

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.

user2357112 supports Monica
  • 215,440
  • 22
  • 321
  • 400
  • Since the OP wants "key-value pairs", shouldn't it be `itertools.islice(your_odict.items(), 0, 10)`? – martineau Dec 29 '20 at 17:07
  • @martineau: It doesn't really matter. You can index the dict to get the values. They went with `for key in some_dict[:10]:` in the question, so I stuck with the closest thing to that in the answer. – user2357112 supports Monica Dec 29 '20 at 17:22