Can I iterate over multiple dictons in a row without merging them?

In python, let's say I have three words:

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 so that each dictionary is repeated sequentially? Something like this, but the syntax here is clearly incorrect:

 for k, v in d1.iteritems(), d2.iteritems(), d3.iteritems(): do_some_stuff(k, v) 

I do not want to combine the dictionaries. The best I can think of is a nested loop below, but it seems like there should be a โ€œmore pythonic, one loopโ€.

 for d in (d1, d2, d3): for k, v in d.iteritems(): do_some_stuff(k, v) 
+4
source share
1 answer

Do 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) 
+10
source

Source: https://habr.com/ru/post/1381562/


All Articles