Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most pythonic way to iterate over OrderedDict

I have an OrderedDict and in a loop I want to get index, key and value. It's sure can be done in multiple ways, i.e.

a = collections.OrderedDict({…}) for i,b,c in zip(range(len(a)), a.iterkeys(), a.itervalues()):   … 

But I would like to avoid range(len(a)) and shorten a.iterkeys(), a.itervalues() to something like a.iteritems(). With enumerate and iteritems it's possible to rephrase as

for i,d in enumerate(a.iteritems()):   b,c = d 

But it requires to unpack inside the loop body. Is there a way to unpack in a for statement or maybe a more elegant way to iterate?

like image 528
Askold Ilvento Avatar asked Jun 25 '15 09:06

Askold Ilvento


People also ask

Can you iterate through a dictionary?

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.


1 Answers

You can use tuple unpacking in for statement:

for i, (key, value) in enumerate(a.iteritems()):     # Do something with i, key, value 

>>> d = {'a': 'b'} >>> for i, (key, value) in enumerate(d.iteritems()): ...     print i, key, value ...  0 a b 

Side Note:

In Python 3.x, use dict.items() which returns an iterable dictionary view.

>>> for i, (key, value) in enumerate(d.items()): ...     print(i, key, value) 
like image 83
falsetru Avatar answered Sep 18 '22 22:09

falsetru