【问题标题】:How to nest the values of a first dictionary into the values of a second dictionary?如何将第一个字典的值嵌套到第二个字典的值中?
【发布时间】:2021-03-09 11:37:48
【问题描述】:

我有两本字典。我想请求您帮助解决以下问题:

  1. 第一个有 339 个键值对。这些值可能具有从 cero 到 10 的随机长度。
  2. 第二个有 215 个键值对。在同样的情况下,这些值的长度是随机的。

第一个字典的值是第二个字典的一个或多个键。有点像这样:

  • dict1=[REQ-1:{value-1, value-2}, REQ-2:{}, REQ-3:{value-3, value-6, value-10},...]
  • dict2=[value-1:{pcr-1,pcr-8}, value-2:{pcr-2,pcr-3,pcr-4},....]

如何将第二个的值嵌套到第一个的值中?:

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:{...}}
,...]

非常感谢您

【问题讨论】:

  • python 中的字典是使用 {} 而不是 [] 创建的。如果您不使用键值对,{} 也是集合的运算符。除此之外,我假设您打算将“REQ-1”等作为字符串,因为python变量名中不允许使用连字符。
  • 是的,你是对的。感谢您发现它。

标签: python python-3.x dictionary nested


【解决方案1】:

您可以通过遍历第一个字典来做到这一点。您可以使用 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}

【讨论】:

  • 非常感谢您的善意贡献,它奏效了!
  • 如果它对你有用,请接受这个答案。
猜你喜欢
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 2021-10-16
  • 1970-01-01
  • 2020-12-30
相关资源
最近更新 更多