【问题标题】:i have two dictionary as stated below. i want to merge it into one nested dictionary我有两本字典,如下所述。我想将它合并到一个嵌套字典中
【发布时间】:2021-06-02 01:04:48
【问题描述】:

a = {'thames': 'low', 'river cam': 'high', 'dickler': 'moderate', 'mil': 'severe', 'bourton': 'low'} b = {'town1': ['thames, bourton'], 'town2': ['river cam'], 'town3': ['dickler','mil']} c = {} d = {}

#这是我的代码

c = {}

d = {}

for key in b.keys():
    c[key] = d
for k,v in a.items():
    if k in b.values():
        d[k] = v

期望的输出: c = {'town1': {'thames':'low', 'bourton': 'low'}, 'town2': {'river cam': 'high'}, 'town3': {'dickler':'中度', 'mil': '严重'}}

【问题讨论】:

  • 您想要的输出不是有效的 Python 语法。你的意思是{'town1': {'thames': 'low', 'bourton': 'low'}, 'town2': {'river cam': 'high'}, 'town3': {'dickler': 'moderate', 'mil': 'severe'}}
  • 哦,对不起,我是这个意思。谢谢
  • 另外,我想['thames, bourton'] 应该是['thames', 'bourton']。反正下面已经有正确答案了。

标签: python dictionary nested key key-value-store


【解决方案1】:
for key,values in b.items():
    c[key] = {}
    for element in values:
        c[key][element] = a[element]

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多