Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over 2 dictionaries using one for loop?

I have two data structures like the following:

DATASET_0 = { 'key1': [ object1, object2, objectN ],
              'key2': [ object3, object4]
            }
DATASET_1 = { 'key1': [ object5, object6, objectN ],
              'key3': [ object7, object8],
              'key4': [ object9, object10],
            }

(This is a highly simplified version but it shows the two top level components - basically a dictionary of lists)

So the same key might appear in both dictionaries but pointing to different objects. Normally I could just merge the two dictionaries on the fly and iterate over the merge but in this case I can't do this. I can't make the top level item a list either.

If the top level item was a list I could do this:

for item in DATASET_0 + DATASET_1:
    blah

Is there anyway to do the same thing using dictionaries?

like image 676
BenH Avatar asked Oct 27 '25 03:10

BenH


2 Answers

itertools.chain is a good friend in times like this.

from itertools import chain

d1 = {'foo': ['bar']}
d2 = {'foo': ['baz']}
for k, v in chain(d1.iteritems(), d2.iteritems()):
   print k, v

If you want to just iterate over the keys, that becomes even easier (and ports to python3.x with no modifications!)

for k in chain(d1, d2):
    print(k)
like image 174
mgilson Avatar answered Oct 29 '25 07:10

mgilson


You can simply concatenate dict.items() lists:

for key, value in DATASET_0.items() + DATASET_1.items():

or chain the dict.iteritems() iterables (using itertools.chain():

from itertools import chain

for key, value in chain(DATASET_0.iteritems(), DATASET_1.iteritems()):
like image 45
Martijn Pieters Avatar answered Oct 29 '25 07:10

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!