我有两本字典。我想请你帮忙解决以下问题:
第一个字典的值是第二个字典中的一个或多个键。就像这样:
如何将第二个值嵌套到第一个值中?:
dict3=[
REQ-1:{value-1:{pcr-1,pcr-8},value-2:{pcr-2,pcr-3,pcr-4}},
REQ-2:{},
REQ-3:{value-3:{...},value-6:{...},value-10:{...}}
,...]
提前谢谢你
发布于 2020-11-26 15:32:22
您可以通过遍历第一个字典来实现这一点。您可以使用for循环或使用字典生成器来完成此操作。
假设第一个字典中的每个值实际上都存在于第二个字典中:
# For loop
dict3 = {} # Create an empty dictionary for us to populate
for key in dict1: # Iter over each of the keys in dict1
subdict = {} # This will be the nested dictionary
for item in dict1[key]: # Iter over each item in the list at that location in the dict
subdict[item] = dict2[item] # Get the corresponding list from dict2 and store it in the nested dictionary
dict3[key] = subdict # store the nested dictionary
# Dictionary generator
dict3 = {key: {item: dict2[item] for item in dict1[key]} for key in dict1}
https://stackoverflow.com/questions/65024600
复制相似问题