Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I iterate over several dicts in succession without merging them?

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)
like image 925
Cloud Artisans Avatar asked Dec 28 '22 11:12

Cloud Artisans


1 Answers

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)
like image 79
Jochen Ritzel Avatar answered Jan 13 '23 11:01

Jochen Ritzel