Python: How to access every kth key in an OrderedDict? | بلاگ

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

تعرفه تبلیغات در سایت

آخرین مطالب

امکانات وب

Vote count: 0

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?

asked 33 secs ago
StatsSorceress

...
نویسنده : استخدام کار بازدید : 11 تاريخ : چهارشنبه 25 بهمن 1396 ساعت: 1:25