Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 864
Indradhanush Gupta Avatar asked Jun 14 '13 04:06

Indradhanush Gupta


1 Answers

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.

like image 135
jamylak Avatar answered Oct 17 '22 06:10

jamylak