# Speed up two for-loops? [closed]

The code below is slow. Any thoughts on speeding up?

dict1 = {}
dict2 = {}
list_needed  = []

for val in dict1.itervalues():
for k,v in d1ct2.iteritems():
if val == k:
list_needed.append([val,v])


Perhaps,

for val in dict1.itervalues():
if val in dict2:
list_needed.append([val,dict2[val]])


This is similar to

list_needed = [[val,dict2[val]] for val in dict1.itervalues() if val in dict2]


My preference would be to make [val,v] a tuple - i.e (val,v) which is an immutable D.S and hence would be faster than a list. But it may not count for much.

• like the list comprehension. But need dict2[val] for additional parse-ing – Merlin Jun 19 '12 at 19:14

Depending on the size of the intersection expected, it might be valuable to let someone else handle the loop & test:

vals = set(dict1.values())
d2keys = set(dict2.keys())
list_needed = [ [val, dict2[val]) for val in vals & d2keys ]


Or, is dict2 disposable? If so, you could do:

for k in set(dict2.keys() - set(dict1.values()):
del dict2[k]
list_needed = dict2.items()


I just came up with those off the top of my head and have no idea how performant they really are.

• list_needed = [ [val, dict2[val]) for val in vals & d2keys ] is much slower than list_needed = [[val,dict2[val]] for val in dict1.itervalues() if val in dict2] – Merlin Jun 20 '12 at 13:45