FaCoffee
FaCoffee

Reputation: 7909

Python: iterating over multiple dictionaries at once

I know from this answer that it is possible to iterate over two different dictionaries at once:

d1 = {'a':5, 'b':6, 'c': 3}
d2 = {'a':6, 'b':7, 'c': 4}
for (k1,v1), (k2,v2) in zip(d1.items(), d2.items()):
    print k1, v1
    print k2, v2

but how can this be efficiently extended to a list with, say, 20 different dictionaries which happen to have the same keys?

mylist=[d1, d2, d3, ..., d20]

Upvotes: 1

Views: 3172

Answers (1)

Adam Smith
Adam Smith

Reputation: 54162

mylist = [d1, d2, d3, ..., d20]
keys = mylist[0].keys()  # they must ALL have the same keys, mind....

for k in keys:
    for d in mylist:
        print k, d[k]

The direct translation would be something like:

for ... in zip(*map(dict.items, mylist)):

but what do you put in the ellipsis? You'd have to either name all those things, or have one big tuple-of-tuples that is difficult to operate on. I guess alternately you could do:

for big_tuple in zip(*map(dict.items, mylist)):
    for kv in big_tuple:
        k, v = kv
        print k, v

but that's longer and harder to handle than just storing the list of keys once and addressing each dictionary separately.

Upvotes: 5

Related Questions