10

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?

Indradhanush Gupta
  • 3,797
  • 9
  • 41
  • 59

2 Answers2

19
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.

Community
  • 1
  • 1
jamylak
  • 120,885
  • 29
  • 225
  • 225
2

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
John La Rooy
  • 281,034
  • 50
  • 354
  • 495
  • Probably worth mentioning *how* the question was unclear - in particular, `product` gives a similar result to iterating the dictionaries in two *nested* for-loops, while jamylak's answer using `zip` gives a similar result to two *adjacent* for-loops. – lvc Jun 14 '13 at 04:38