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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With