【问题标题】:Merge two dictionaries while sharing the keys在共享密钥的同时合并两个字典
【发布时间】:2012-10-18 13:36:26
【问题描述】:

我正在尝试构建一个小程序,给定一个包含姓名和地址的字典以及另一个包含姓名和电话号码的字典,输出应该将它们合并(而不是相互覆盖)。最终输出字典应包含姓名、地址(如果可用)和电话(如果可用)。 这是一个例子:

addr = {'George': 'via Wagner, 23', 'White': 'Piazza Bologna, 1',
    'L. Red': 'via A. Einstein, 12', 'Pete': 'via Pio'}
phone = {'Mark': '347 8987989', 'George': '06 89786765',
     'Mauro B.': '3489878675', 'Pete': '07897878', 'L. Red': '09877887'}

最后的字典:

addr_phone(addr, phone) -->
{'George':    {'address': 'via Wagner, 23'},
 'Mark':      {'phone': '347 8987989'},
 'George':    {'phone': '06 89786765'},
 'L. Red':   {'phone': '09877887', 'address': 'via A. Einstein, 12'},
 'Pete':       {'phone': '07897878', 'address': 'via Pio'},
 'Mauro B.':   {'phone': '3489878675'},
 'White': {'address': 'Piazza Bologna, 1'}}

我试着写这个:

def addr_phone(addr, phone):
    d3={}
    d3.update(addr)
    d3.update(phone)
    for k,v in phone.items():
        if k not in addr:
            d3[k]=v
    return d3

但是我得到了多个同名实例,这不是我想要的。 感谢您的帮助。

【问题讨论】:

  • 你怎么能把'george'作为字典中的相同键。它违反了字典的定义。
  • @Srikar 你能说得更具体点吗?它使用 Martijn 的解决方案完美运行。

标签: dictionary merge python-3.x


【解决方案1】:

使用defaultdict

from collections import defaultdict

out = defaultdict(dict)
for name, phonenumber in phone.iteritems():
    out[name]['phone'] = phonenumber
for name, address in addr.iteritems():
    out[name]['address'] = address

对于 python 3,只需将 .iteritems() 替换为 .items()

out = defaultdict(dict)
for name, phonenumber in phone.items():
    out[name]['phone'] = phonenumber
for name, address in addr.items():
    out[name]['address'] = address

您确实需要遍历两个输入字典,因为您要将值移动到每个名称的新字典中。

【讨论】:

  • 正要发布相同的内容:)。要完整,请将from collections import defaultdict 添加到顶部。
  • @jro:我开始明白了。 :-P
  • 给我这个错误:AttributeError: 'dict' object has no attribute 'iteritems'
  • @test123 表示您使用的是 Python 3。然后将其更改为 items()
  • @test123:糟糕:-P 很高兴它有帮助!
猜你喜欢
  • 2022-12-24
  • 2016-06-20
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
  • 2019-11-11
  • 2012-08-23
  • 2021-08-25
  • 2021-08-28
相关资源
最近更新 更多