0

I am looking to merge dictionaries in Python with dictionaries that have a common value then key. Currently, I have a nasty loop inside of a loop inside of a loop. There has to be a better way...

What I have is one dictionary with a single digit key and a list of numbers for that value, then a second dictionary with a key that corresponds with one of the numbers in the value list and a float associated with that number. They are formatted like this (although much larger):

dict1 = {0:[3, 5, 2, 7], 1:[1, 4, 0, 6]}
dict2 = {0:0.34123, 1:0.45623, 2:0.76839, 3:0.32221, 4:0.871265, 5:0.99435, 6:0.28665, 7:0.01546}

And I would like to merge them so they look like this:

dict3 = {0:[0.32221, 0.99435, 0.76839, 0.01546], 1:[0.45623, 0.871265, 0.034123, 0.28665]}

Is there a simpler way to do this than several nested for loops? Any help would be massively appreciated!

1
  • 4
    Merge them in what way? I really don't see some any obvious correlation between the numbers
    – Voo
    May 29, 2013 at 21:14

3 Answers 3

3

You can do this using a nested list comprehension inside a dict comprehension:

dict3 = {k: [dict2[i] for i in v] for k, v in dict1.items()}

This will basically iterate through all k/v-combinations within the first dictionary. The k is kept as the key for the resulting dictionary, and the v is a list of all indices in dict2 which values should be used. So we iterate through the elements in v and collect all items from dict2 we want to take, combine those in a list (using the list comprehension) and use that result as the value of the result dictionary.

0
2
>>> dict1 = {0:[3, 5, 2, 7], 1:[1, 4, 0, 6]}
>>> dict2 = {0:0.34123, 1:0.45623, 2:0.76839, 3:0.32221, 4:0.871265, 5:0.99435, 6:0.28665, 7:0.01546}
>>> {k:[dict2[m] for m in v] for k, v in dict1.items()}
{0: [0.32221, 0.99435, 0.76839, 0.01546], 1: [0.45623, 0.871265, 0.34123, 0.28665]}
1
  • You converged on the same answer as @poke above. Thank you!
    – Micrasema
    May 29, 2013 at 21:25
0

And yet another dictionary comprehension, but with map...

dict3={k: map(lambda x: dict2[x],dict1[k]) for k in dict1.iterkeys()}

Your Answer

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

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