python - What is the most pythonic way to iterate over OrderedDict -
i have ordereddict , in loop want index, key , value. it's sure can done in multiple ways, i.e.
a = collections.ordereddict({…}) i,b,c in zip(range(len(a)), a.iterkeys(), a.itervalues()): …
but avoid range(len(a)) , shorten a.iterkeys(), a.itervalues() a.iteritems(). enumerate , iteritems it's possible rephrase as
for i,d in enumerate(a.iteritems()): b,c = d
but requires unpack inside loop body. there way unpack in statement or maybe more elegant way iterate?
you can use tuple unpacking in for
statement:
for i, (key, value) in enumerate(a.iteritems()): # i, key, value
>>> d = {'a': 'b'} >>> i, (key, value) in enumerate(d.iteritems()): ... print i, key, value ... 0 b
side note:
in python 3.x, use dict.items()
returns iterable dictionary view.
>>> i, (key, value) in enumerate(d.items()): ... print(i, key, value)
Comments
Post a Comment