如何使用相同的主键组合两个嵌套字典

发布于 2025-01-15 04:24:30 字数 1118 浏览 1 评论 0原文

我有两个具有相同主键的嵌套字典:

dict1 = {'person1': {'name': 'John', 'sex': 'Male'},
         'person2': {'name': 'Marie', 'sex': 'Female'},
         'person3': {'name': 'Luna', 'sex': 'Female'},
         'person4': {'name': 'Peter', 'sex': 'Male'}}

dict2 = {'person1': {'weight': '81.1', 'age': '27'},
         'person2': {'weight': '56.7', 'age': '22'},
         'person3': {'weight': '63.4', 'age': '24'},
         'person4': {'weight': '79.1', 'age': '29'}}

所以我想通过 dict2 中的键值对来丰富 dict 1。

我可以用 for 循环来做到这一点...

for key in dict2:
        dict2[key]['age'] = dict1[key]['age']
        dict2[key]['weight'] = dict2[key]['weight']

结果:

dict2 = {'person1': {'name': 'John', 'sex': 'Male', 'weight': '81.1', 'age': '27'},
         'person2': {'name': 'Marie', 'sex': 'Female', 'weight': '56.7', 'age': '22'},
         'person3': {'name': 'Luna', 'sex': 'Female', 'weight': '63.4', 'age': '24'},
         'person4': {'name': 'Peter', 'sex': 'Male', 'weight': '79.1', 'age': '29'}}

...但是有没有一种更 Pythonic 的方法来做到这一点 - 例如使用 dict 理解?

I have two nested dicts with same master keys:

dict1 = {'person1': {'name': 'John', 'sex': 'Male'},
         'person2': {'name': 'Marie', 'sex': 'Female'},
         'person3': {'name': 'Luna', 'sex': 'Female'},
         'person4': {'name': 'Peter', 'sex': 'Male'}}

dict2 = {'person1': {'weight': '81.1', 'age': '27'},
         'person2': {'weight': '56.7', 'age': '22'},
         'person3': {'weight': '63.4', 'age': '24'},
         'person4': {'weight': '79.1', 'age': '29'}}

So I want to enrich dict 1 by the key value pairs from dict2.

I'm able to do so with a for loop...

for key in dict2:
        dict2[key]['age'] = dict1[key]['age']
        dict2[key]['weight'] = dict2[key]['weight']

Result:

dict2 = {'person1': {'name': 'John', 'sex': 'Male', 'weight': '81.1', 'age': '27'},
         'person2': {'name': 'Marie', 'sex': 'Female', 'weight': '56.7', 'age': '22'},
         'person3': {'name': 'Luna', 'sex': 'Female', 'weight': '63.4', 'age': '24'},
         'person4': {'name': 'Peter', 'sex': 'Male', 'weight': '79.1', 'age': '29'}}

...but is there a more pythonic way to do so - e.g. with dict comprehension?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

破晓 2025-01-22 04:24:30

是的:

dict3 = {k: {**v, **dict2[k]} for k, v in dict1.items()}

首先,使用 .items() 同时迭代键和值。

然后,对于每个键 k,您希望该值是通过转储(或解构)vdict2[k]在其中。

Python 更新 >= 3.9

感谢 @mwo 提到管道 | 操作数:

dict3 = {k: v | dict2[k] for k, v in dict1.items()}

Yes:

dict3 = {k: {**v, **dict2[k]} for k, v in dict1.items()}

Firstly, use .items() to iterate over both keys and values at the same time.

Then, for each key k you want the value to be a new dict that is created by dumping — or destructuring — both v and dict2[k] in it.

UPDATE for Python >= 3.9:

Thanks @mwo for mentioning the pipe | operand:

dict3 = {k: v | dict2[k] for k, v in dict1.items()}
无戏配角 2025-01-22 04:24:30

如果您可以控制数据源,请展平字典,然后使用 update 方法。例如:

dict1 = {('person1', 'name'): 'John'}
dict2 = {('person1', 'weight'): 81.1}
dict1.update(dict2)
>>> dict1
{('person1', 'name'): 'John', 
 ('person1', 'weight'): 81.1}

处理这种数据结构要容易得多,但如果您受困于嵌套字典,您可以使用 NestedDict 通过类似的接口实现相同的结果。

from ndicts import NestedDict

nd1 = NestedDict(dict1) 
nd2 = NestedDict(dict2) 
nd1.update(nd2)
>>> nd1
NestedDict(
    {'person1': {'name': 'John', 'weight': 81.1}}
)

如果您需要结果作为字典,请使用 nd1.to_dict() 。

安装ndicts pip install ndicts

If you have control over the data source flatten the dictionaries and then use the update method. For example:

dict1 = {('person1', 'name'): 'John'}
dict2 = {('person1', 'weight'): 81.1}
dict1.update(dict2)
>>> dict1
{('person1', 'name'): 'John', 
 ('person1', 'weight'): 81.1}

It is much easier to deal with this kind of data structure, but if you are stuck with nested dictionaries you can use a NestedDict to achieve the same result with a similar interface.

from ndicts import NestedDict

nd1 = NestedDict(dict1) 
nd2 = NestedDict(dict2) 
nd1.update(nd2)
>>> nd1
NestedDict(
    {'person1': {'name': 'John', 'weight': 81.1}}
)

Use nd1.to_dict() if you need the result as a dictionary.

To install ndicts pip install ndicts.

哥,最终变帅啦 2025-01-22 04:24:30

答案不考虑要合并的字典中深度超过 2 的级别,
要合并到任意深度,请使用以下递归:

def merge_nested_dicts(dict1, dict2):
    res = {}
    for key, value in dict1.items():
        if key in dict2:
            res[key] = merge_nested_dicts(dict1[key], dict2[key])
            del dict2[key]
        else:
            res[key]=value
    res.update(dict2)
    return res

The answers do not consider levels deeper than 2 in the dicts to be merged,
to merge to any depth use the following recursion:

def merge_nested_dicts(dict1, dict2):
    res = {}
    for key, value in dict1.items():
        if key in dict2:
            res[key] = merge_nested_dicts(dict1[key], dict2[key])
            del dict2[key]
        else:
            res[key]=value
    res.update(dict2)
    return res
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文