简体   繁体   中英

Python: How to access every kth key in an OrderedDict?

I have an OrderedDict (the keys are ordered):

od1 = {0:10, 1:3, 2:7, 3:11, 4:30, 5:15, 6:19, 7:4, 8:3}

I want a new OrderedDict() object that contains the key:value pairs of every second element of od1 . That is, I want:

od2 = {0:10, 2:7, 4:30, 6:19, 8:3}

I have tried:

od2 = OrderedDict()
od2 = {k:v for k, v in od1.items() if k % 2 == 0}

However, that does not give me an ordered dictionary, and it does not give me all keys. Instead, I get this, which is NOT what I want:

{0: 10, 8: 3, 2: 7, 4: 30, 6: 19}

How can I get a new OrderedDict() object that contains every kth key and its associated value?

Use itertools.islice on the od.items :

>>> od
OrderedDict([(0, 10), (1, 3), (2, 7), (3, 11), (4, 30), (5, 15), (6, 19), (7, 4), (8, 3)])

Then simply:

>>> from itertools import islice
>>> OrderedDict(islice(od.items(), None, None, 2))
OrderedDict([(0, 10), (2, 7), (4, 30), (6, 19), (8, 3)])

Or, for example, every third key:

>>> OrderedDict(islice(od.items(), None, None, 3))
OrderedDict([(0, 10), (3, 11), (6, 19)])

islice works analogously to list slicing, eg. my_list[::2] or my_list[::3] , however, it works on any iterable, doesn't support negative step values, and you must use explicit None values, but the principles are the same.

Since you are starting with ordered dict you can just simply use this snippet (Python2.7):

from collections import OrderedDict

od1 = OrderedDict([(0, 10), (1, 3), (2, 7), (3, 11), (4, 30), (5, 15), (6, 19), (7, 4), (8, 3)])
c = od1.items()[::2]

print OrderedDict(c)  # OrderedDict([(0, 10), (2, 7), (4, 30), (6, 19), (8, 3)])

For Python 3.6 it is a slightly different:

from collections import OrderedDict

od1 = OrderedDict([(0, 10), (1, 3), (2, 7), (3, 11), (4, 30), (5, 15), (6, 19), (7, 4), (8, 3)])
c = list(od1.items())[::2]
print(OrderedDict(c)) # OrderedDict([(0, 10), (2, 7), (4, 30), (6, 19), (8, 3)])

You can use enumerate :

import collections
new_d = collections.OrderedDict([a for i, a in enumerate(od1.items()) if i%2 == 0])

Output:

OrderedDict([(0, 10), (2, 7), (4, 30), (6, 19), (8, 3)])
 od1 = {0:10, 1:3, 2:7, 3:11, 4:30, 5:15, 6:19, 7:4, 8:3}
 od2=sorted([(key,item) for key,item in od1.items() if key%2==0])
 print(od2)

output:

 [(0, 10), (2, 7), (4, 30), (6, 19), (8, 3)]

od2 type is 'dict' that is why you are getting unordered dict.

>>> type(od2)
<class 'dict'>

quick solutions will be like this:

>>> od2 = OrderedDict({k:v for k, v in od.items() if k % 2 == 0})
>>> od2
OrderedDict([(0, 10), (2, 7), (4, 30), (6, 19), (8, 3)])

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