共享密钥时合并两个字典 [英] Merge two dictionaries while sharing the keys

查看:60
本文介绍了共享密钥时合并两个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to build a small program that, given a dictionary containing names and addresses and another dictionary that contains names and phone numbers, the output should merge them both (and not overwrite one another). The final output dictionary should contain name, address (if available) and phone (if available). Here's an example:

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

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

But I get multiple instances of the same name, and it's not what I want. Thanks for your help.

推荐答案

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

For python 3 just replace .iteritems() with .items():

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

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

You do need to loop over both input dictionaries, because you are moving the values to a new dictionary per name.

这篇关于共享密钥时合并两个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆