合并Python中的字典层次结构 [英] Merging hierarchy of dictionaries in Python

查看:200
本文介绍了合并Python中的字典层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字典,我想做的有点奇怪.基本上,我想将它们合并.这很简单.但是它们是字典的层次结构,我想以这样的方式合并它们:如果字典中的一项本身就是字典并且在两者中都存在,那么我也想合并这些字典.如果不是字典,我希望第二个字典中的值覆盖第一个字典中的值.像这样的东西:

I have two dictionaries, and what I'm trying to do is a bit odd. Basically, I want to merge them. That's simple enough. But they're hierarchies of of dictionaries, and I want to merge them in such a way that if an item in a dictionary is itself a dictionary and exists in both, I want to merge those dictionaries as well. If it's not a dictionary, I want the values from the second dictionary to overwrite the values from the first one. Something sort of like this:

a = {0: {0: "a"},
     1: [0, 1, 2]}

b = {0: {1: "b"},
     1: [3, 4, 5]}

Merge(a, b)

#output:
{0: {0: "a",
     1: "b"},
 1: [3, 4, 5]}

这有意义吗?因为键"0"在a和b中都包含字典,所以它也合并了这些字典.但是在第二把钥匙的情况下,它是一个列表,因此只覆盖了它.

Does that make sense? Because the key "0" contained a dictionary in both a and b, it merged those dictionaries as well. But in the case of the second key, it was a list so it just overwrote it.

所以我想我将要研究某种递归函数?不太确定如何处理这个问题.

So I suppose I'll be looking at some kind of recursive function? Not quite sure how to approach this one.

谢谢!

我忘了提到一个非常关键的细节:

I forgot to mention one pretty crucial detail:

我需要一个在2.6.2和2.7.3中都可以使用的函数.

I need a function that works in both 2.6.2 and 2.7.3.

推荐答案

假设您可能有嵌套的字典(基于您对递归的看法),类似的东西应该可以工作,

Assuming you might have nested dictionaries (based on your thinking in terms of recursion), something like this should work,

from copy import deepcopy

def merge(a, b):
    if isinstance(b, dict) and isinstance(a, dict):
        a_and_b = a.viewkeys() & b.viewkeys()
        every_key = a.viewkeys() | b.viewkeys()
        return {k: merge(a[k], b[k]) if k in a_and_b else 
                   deepcopy(a[k] if k in a else b[k]) for k in every_key}
    return deepcopy(b)

从概念上讲,merge(a, b)的返回值类似于创建a的(深层)副本并运行a.update(b)的递归版本.

The return value of merge(a, b) is conceptually like creating a (deep) copy of a and running a recursive version of a.update(b).

使用一些嵌套示例,

a = {0: {0: 'a'},
     1: [0, 1, 2],
     2: [9, 9],
     3: {'a': {1: 1, 2: 2}, 'b': [0, 1]}}

b = {0: {1: 'b'},
     1: [3, 4, 5],
     2: {22: 22, 33: 33},
     3: {'a': {2: 22, 3: 33}, 'b': [99, 88]}}

merge(a, b)产生

{0: {0: 'a', 1: 'b'},
 1: [3, 4, 5],
 2: {22: 22, 33: 33},
 3: {'a': {1: 1, 2: 22, 3: 33}, 'b': [99, 88]}}

Python 2.6版本

def merge(a, b):
    if isinstance(b, dict) and isinstance(a, dict):
        a_and_b = set(a).intersection(b)
        every_key = set(a).union(b)
        return dict((k, merge(a[k], b[k]) if k in a_and_b else
                     deepcopy(a[k] if k in a else b[k])) for k in every_key)
    return deepcopy(b)

这篇关于合并Python中的字典层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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