2
\$\begingroup\$

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])
\$\endgroup\$

closed as off-topic by Billal Begueradj, t3chb0t, Sᴀᴍ Onᴇᴌᴀ, Stephen Rauch, Dannnno Jun 10 '18 at 16:31

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – Billal Begueradj, t3chb0t, Sᴀᴍ Onᴇᴌᴀ, Stephen Rauch, Dannnno
If this question can be reworded to fit the rules in the help center, please edit the question.

4
\$\begingroup\$

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.

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

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.

\$\endgroup\$
  • \$\begingroup\$ 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] \$\endgroup\$ – Merlin Jun 20 '12 at 13:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.