我有两个字典。实际上,它们更长。 首先:
Data = { "AT" : [1,2,3,4], "BE" : [ 4,2,1,6], "DE" : [ 5,7,8,9] }
第二个字典:
Data2 = { "AT" : ["AT1","AT2","AT3"], "BE" : ["BE1","BE2","BE3"], "DE" : ["DE1","DE2","DE3","DE4","DE5"] }
我现在想要一个字典,该字典将第一个的值分配给这些值 第二个字典的值(第二个字典的值是新键。)
类似的东西:
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... }
我尝试过:
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)
我得到的值太多,无法解包错误,尽管我不太确定这是否符合我的要求:/
错误:
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
谢谢您的帮助。
答案 0 :(得分:3)
这是使用字典理解的一种方法:
document.write
输出:
result = {y : Data[x] for x in Data2 for y in Data2[x]}
答案 1 :(得分:0)
不用理解的方法。
result = {}
for k,v in Data2.items():
for _v in v:
result[_v]=Data[k]
print(result)