Reputation: 47
I have two dictionaries. In reality they are much longer. First:
Data = { "AT" : [1,2,3,4], "BE" : [ 4,2,1,6], "DE" : [ 5,7,8,9] }
2nd dict:
Data2 = { "AT" : ["AT1","AT2","AT3"], "BE" : ["BE1","BE2","BE3"], "DE" : ["DE1","DE2","DE3","DE4","DE5"] }
I now want a dictionary that assigns the values of the first to the values of the 2nd dictionary (the values of the 2nd dictionary are the new keys.)
Something like:
Result = { "AT1" : [1,2,3,4], "AT2" : [1,2,3,4], "AT3" : [1,2,3,4], "BE1" : [4,2,1,6], "BE2" : [4,2,1,6] and so on... }
I tried:
search= {k : v for k, v in Data.itervalues()}
result = {search[v]: k for v in Data2.itervalues() for k in Data.itervalues()}
print(result)
I get a too many values to unpack error and despite that im not quite sure if this does what i want it to do :/
Error:
Traceback (most recent call last):
File "<ipython-input-18-e4ca3008cc18>", line 17, in <module>
search= {k : v for k, v in Data.itervalues()}
File "<ipython-input-18-e4ca3008cc18>", line 17, in <dictcomp>
search= {k : v for k, v in Data.itervalues()}
ValueError: too many values to unpack
Thanks for any help in advance.
Upvotes: 1
Views: 49
Reputation: 3331
Here is a way to do it using a dictionary comprehension :
result = {y : Data[x] for x in Data2 for y in Data2[x]}
Output :
{'AT1': [1, 2, 3, 4],
'AT2': [1, 2, 3, 4],
'AT3': [1, 2, 3, 4],
'BE1': [4, 2, 1, 6],
'BE2': [4, 2, 1, 6],
'BE3': [4, 2, 1, 6],
'DE1': [5, 7, 8, 9],
'DE2': [5, 7, 8, 9],
'DE3': [5, 7, 8, 9],
'DE4': [5, 7, 8, 9],
'DE5': [5, 7, 8, 9]}
Upvotes: 3
Reputation: 578
Way without using comprehension.
result = {}
for k,v in Data2.items():
for _v in v:
result[_v]=Data[k]
print(result)
Upvotes: 0