Indradhanush Gupta
Indradhanush Gupta

Reputation: 4237

How to travese two dictionaries in a single for loop?

I want to generate the following effect :

for i, j in d.items() and k, v in c.items():
    print i, j, k, v

This is wrong. I want to know how can I achieve this?

Upvotes: 10

Views: 3071

Answers (2)

John La Rooy
John La Rooy

Reputation: 304355

You question doesn't make it clear, whether you want to iterate the dictionaries in two nested for-loops, or side by side (as done in @jamylak's answer)

Here is the nested interpretation

from itertools import product
for (i, j), (k, v) in product(d.items(), c.items()):
    print i, j, k, v

eg

>>> d={'a':'Apple', 'b':'Ball'}
>>> c={'1':'One', '2':'Two'}
>>> from itertools import product
>>> for (i, j), (k, v) in product(d.items(), c.items()):
...     print i, j, k, v
... 
a Apple 1 One
a Apple 2 Two
b Ball 1 One
b Ball 2 Two

Upvotes: 2

jamylak
jamylak

Reputation: 133634

for (i, j), (k, v) in zip(d.items(), c.items()):
   print i, j, k, v

Remember the order will be arbitrary unless your dictionaries are OrderedDicts. To be memory efficient

In Python 2.x (where dict.items and zip create lists) you can do the following:

from itertools import izip
for (i, j), (k, v) in izip(d.iteritems(), c.iteritems()):
   print i, j, k, v

This won't necessarily be faster, as you will observe on small lists it's faster to iterate over these intermediate lists however you will notice a speed improvement when iterating very large data structures.

In Python 3.x zip is the same as izip (which no longer exists) and dict.items (dict.iteritems no longer exists) returns a view instead of a list.

Upvotes: 19

Related Questions