Pythonic方法将键/值从一个字典复制到另一个字典

bry*_*yan 1 python dictionary

我正在寻找一种简洁的方法来获取具有共同键/值的两个dicts,并将键和值复制到其中一个dicts中.例:

d1 = [{'name': 'john', 'uid': 'ax01', 'phone': '555-555-5555'},
    {'name': 'jane', 'uid': 'ax02', 'phone': '555-555-5555'},
    {'name': 'jimmy', 'uid': 'ax03', 'phone': '555-555-5555'}]

d2 = [{'uid': 'ax01', 'orderid': '9999', 'note': 'testing this'},
      {'uid': 'ax02', 'orderid': '6666', 'note': 'testing this'},
      {'uid': 'ax03', 'orderid': '7777', 'note': 'testing this'}]
Run Code Online (Sandbox Code Playgroud)

uid是我想要用来复制orderid密钥和该匹配数据点的值的密钥.最后我会得到类似的东西:

output = [
    {'name': 'john', 'uid': 'ax01', 'phone': '555-555-5555', 'orderid': '9999'},
    {'name': 'jane', 'uid': 'ax02', 'phone': '555-555-5555', 'orderid': '6666'},
    {'name': 'jimmy', 'uid': 'ax03', 'phone': '555-555-5555', 'orderid': '7777'}
]
Run Code Online (Sandbox Code Playgroud)

orderid被拉入d1.如果可能的话,我正在寻找pythonic方式.

Mar*_*ers 5

您可以使用dict()复制一个字典并传入额外的密钥.您需要创建从第一个uidorderid第一个的映射:

uid_to_orderid = {d['uid']: d['orderid'] for d in d2}
output = [dict(d, orderid=uid_to_orderid[d['uid']]) for d in d1]
Run Code Online (Sandbox Code Playgroud)

这假定您希望d1保持字典保持不变.其他假设是uid值是唯一的,并且所有uidd1都存在于中d2.

演示:

>>> d1 = [{'name': 'john', 'uid': 'ax01', 'phone': '555-555-5555'},
...     {'name': 'jane', 'uid': 'ax02', 'phone': '555-555-5555'},
...     {'name': 'jimmy', 'uid': 'ax03', 'phone': '555-555-5555'}]
>>> d2 = [{'uid': 'ax01', 'orderid': '9999', 'note': 'testing this'},
...       {'uid': 'ax02', 'orderid': '6666', 'note': 'testing this'},
...       {'uid': 'ax03', 'orderid': '7777', 'note': 'testing this'}]
>>> uid_to_orderid = {d['uid']: d['orderid'] for d in d2}
>>> [dict(d, orderid=uid_to_orderid[d['uid']]) for d in d1]
[{'orderid': '9999', 'phone': '555-555-5555', 'name': 'john', 'uid': 'ax01'}, {'orderid': '6666', 'phone': '555-555-5555', 'name': 'jane', 'uid': 'ax02'}, {'orderid': '7777', 'phone': '555-555-5555', 'name': 'jimmy', 'uid': 'ax03'}]
Run Code Online (Sandbox Code Playgroud)