我正在寻找一种简洁的方法来获取两个具有公共(public)键/值的字典,并将键和值复制到其中一个字典中。示例:
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
是我想用来复制 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'}
]
其中 orderid
被拉入 d1
。如果可能的话,我正在寻找 pythonic 方式。
最佳答案
您可以使用dict()
复制一个字典并传入额外的键。不过,您首先需要创建一个从 uid
到 orderid
的映射:
uid_to_orderid = {d['uid']: d['orderid'] for d in d2}
output = [dict(d, orderid=uid_to_orderid[d['uid']]) for d in d1]
这假设您希望保留 d1
中的字典,否则将保持不变。所做的其他假设是 uid
值是唯一的,并且 d1
中的所有 uid
值都存在于 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'}]
关于将键/值从一个字典复制到另一个字典的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21760188/