In python, let's say I have three dicts:
d1, d2, d3 = {...}, {...}, {...}
I need to iterate over each of them and perform the same operation:
for k, v in d1.iteritems():
do_some_stuff(k, v)
for k, v in d3.iteritems():
do_some_stuff(k, v)
for k, v in d3.iteritems():
do_some_stuff(k, v)
Is there a way to do this in one loop, such that each dictionary is iterated over in succession? Something like this, but the syntax is obviously incorrect here:
for k, v in d1.iteritems(), d2.iteritems(), d3.iteritems():
do_some_stuff(k, v)
I don't want to merge the dictionaries. The best I can come up with is the nested loop below, but it seems like there should be "a more pythonic, single loop way."
for d in (d1, d2, d3):
for k, v in d.iteritems():
do_some_stuff(k, v)
You want chain
:
from itertools import chain
for k,v in chain(d1.iteritems(), d2.iteritems(), d3.iteritems()):
do_some_stuff(k, v)
or more general
ds = d1,d2,d3
for k,v in chain.from_iterable(d.iteritems() for d in ds):
do_some_stuff(k, v)
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