首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将第一个字典的值嵌套到第二个字典的值中?

如何将第一个字典的值嵌套到第二个字典的值中?
EN

Stack Overflow用户
提问于 2020-11-26 15:07:02
回答 1查看 34关注 0票数 2

我有两本字典。我想请你帮忙解决以下问题:

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

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

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

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

代码语言:javascript
运行
复制
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:{...}}
,...]

提前谢谢你

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-26 15:32:22

您可以通过遍历第一个字典来实现这一点。您可以使用for循环或使用字典生成器来完成此操作。

假设第一个字典中的每个值实际上都存在于第二个字典中:

代码语言:javascript
运行
复制
# 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}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65024600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档