合并Python 2.7中的多嵌套词典的最佳方法 [英] The best way to merge multi-nested dictionaries in Python 2.7

查看:122
本文介绍了合并Python 2.7中的多嵌套词典的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个嵌套的字典,我想将它们合并为一个(第二个dict覆盖第一个dict值).我看到了许多用于合并平面"(非嵌套)字典的漂亮解决方案,例如:

I have two nested dictionaries and I want to merge them into one (where second dict overrides first dict values). I saw a lot of beautiful solutions for merging "flat" (not nested) dictionaries, e.g.:

dict_result = dict1.copy()
dict_result.update(dict2)

dict_result = dict(dict1.items() + dict2.items())

或(我最喜欢的人)

dict_result = dict(d1,**d2)

但找不到最有效的方法来合并多嵌套字典.

but couldn't find the most efficient way to merge multi-nested dicts.

我正在尝试避免递归.你的主张是什么?

I'm trying to avoid recursion. What is your proposition?

推荐答案

除非严格限制合并字典的深度,否则无法避免递归. 1)此外,也没有公告或库函数来执行此操作(也就是说,我所不知道的),但这实际上并不难.这样的事情应该做:

Unless the depth of the dictionaries to merge is strictly limited, there's no way to avoid recursion.1) Also, there's no bultin or library function to do this (that is, none that I know of), but it's actually not all that hard. Something like this should do:

def merge(d1, d2):
    for k in d2:
        if k in d1 and isinstance(d1[k], dict) and isinstance(d2[k], dict):
            merge(d1[k], d2[k])
        else:
            d1[k] = d2[k]   

这是什么:迭代d2中的键,并且如果也可以在d1中找到该键并且它们都是字典,则合并这些子字典,否则用<中的值覆盖d1中的值c0>.请注意,这会更改d1及其子字典 ,因此您可能需要对其进行深度复制.

What this does: It iterates the keys in d2 and if the key can also be found in d1 and both are dictionaries, merge those sub-dictionaries, otherwise overwrite the value in d1 with that from d2. Note that this changes d1 and its sub-dictionaries in place, so you might want to deep-copy it before.

或使用此版本创建合并的副本:

Or use this version to create a merged copy:

def merge_copy(d1, d2):
    return {k: merge_copy(d1[k], d2[k]) if k in d1 and isinstance(d1[k], dict) and isinstance(d2[k], dict) else d2[k] for k in d2}

示例:

>>> d1 = {"foo": {"bar": 23, "blub": 42}, "flub": 17}
>>> d2 = {"foo": {"bar": 100}, "flub": {"flub2": 10}, "more": {"stuff": 111}}
>>> merge(d1, d2)
>>> print d1
{'foo': {'bar': 100, 'blub': 42}, 'flub': {'flub2': 10}, 'more': {'stuff': 111}}


1)您可以使用堆栈进行迭代,但这只会使事情变得更加复杂,并且应该这样做以避免出现最大递归深度的问题.


1) You can make it iterative, using a stack, but this will only make things more complicated and should only be done to avoid problems with maximum recursive depth.

这篇关于合并Python 2.7中的多嵌套词典的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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