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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.