繁体   English   中英

从一个字典的键和另一个字典 python 的对应值创建字典

[英]Create a dictionary from the keys of one dictionary and corresponding values of another dictionary python

我有两个字典,一个是这样的:

dict1 = {'1': ['1000', '2000', '3000']}

另一个是:

dict2 = {'1000': ['12', '13', '14'], '2000': ['15', '16', '17'], '3000': ['18', '19', '20']}

有没有办法制作一本像这样的新字典?:

dict3 = {'1':[['12', '13', '14'], ['15', '16', '17'], ['18', '19', '20']]}

您可以使用列表和字典理解来做到这一点:

dict3 = {k:[dict2[i] for i in v] for k,v in dict1.items()}
print(dict3) # output: {'1': [['12', '13', '14'], ['15', '16', '17'], ['18', '19', '20']]}

您可以在没有冗余变量的情况下进行 list+dict 理解:

dict1 = {'1': ['1000', '2000', '3000']}
dict2 = {'1000': ['12', '13', '14'], '2000': ['15', '16', '17'], '3000': ['18', '19', '20']}

dict3 = {key: [dict2[value] for value in dict1[key]] for key in dict1}
print(dict3)

Output:

{'1': [['12', '13', '14'], ['15', '16', '17'], ['18', '19', '20']]}

外部的 dict 理解遍历dict1中的键。

内部列表推导通过收集 dict2 中的所有值来构建该条目的值,这些值由dict2中给出的dict2键列表dict1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM