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

标签 python dictionary

我正在寻找一种简洁的方法来获取两个具有公共(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() 复制一个字典并传入额外的键。不过,您首先需要创建一个从 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]

这假设您希望保留 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/

相关文章:

Python:字典值指针是否存储其键?

python - 如何使用 List Comprehensions 在一行中打印列表中的一系列整数?

Python Django 模板无法从模型函数获取名称

ios - 如何使用 swift 从 JSON 中提取数据

python - 坚持使用 UTF-8 作为默认编码

python - 如何为 scikit-learn 分类器获取信息量最大的特征?

python - 从数据文件中获取带有列标题和数据列的 python 映射

iOS - 在 swift 3 中打印和存储字典数组

python - 使用 map 函数代替 for 循环

c - 字符串的哈希函数