Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将一个字典的值添加到另一个字典_Python - Fatal编程技术网

Python 将一个字典的值添加到另一个字典

Python 将一个字典的值添加到另一个字典,python,Python,我想将一本词典的值添加到另一本词典中。例如: adict = {1: {'a': 13, 'b': 19, 'c': 15}, 2: {'a': 7, 'b': 2, 'c': 0}} 如果我们将{1:{'a':3,'b':9,'c':23}添加到adict 那么adict现在应该是: {1: {'a': 16, 'b': 28, 'c': 38}, 2: {'a': 7, 'b': 2, 'c': 0}} {1: {'a': 16, 'b': 28, 'c': 38}, 2: {'a':

我想将一本词典的值添加到另一本词典中。例如:

adict = {1: {'a': 13, 'b': 19, 'c': 15}, 2: {'a': 7, 'b': 2, 'c': 0}}
如果我们将
{1:{'a':3,'b':9,'c':23}
添加到adict

那么adict现在应该是:

{1: {'a': 16, 'b': 28, 'c': 38}, 2: {'a': 7, 'b': 2, 'c': 0}}
{1: {'a': 16, 'b': 28, 'c': 38}, 2: {'a': 7, 'b': 2, 'c': 0}, 3: {'a': 4}}
{1: {'a': 16, 'b': 28, 'c': 38}, 2: {'a': 8, 'b': 10, 'c': 27, 'd': 11}, 3: {'a': 4}}
如果我们添加
{3:{'a':4}
,那么adict现在应该是:

{1: {'a': 16, 'b': 28, 'c': 38}, 2: {'a': 7, 'b': 2, 'c': 0}}
{1: {'a': 16, 'b': 28, 'c': 38}, 2: {'a': 7, 'b': 2, 'c': 0}, 3: {'a': 4}}
{1: {'a': 16, 'b': 28, 'c': 38}, 2: {'a': 8, 'b': 10, 'c': 27, 'd': 11}, 3: {'a': 4}}
如果我们加上
{2:{'a':1,'b':8,'c':27,'d':11}

那么adict现在应该是:

{1: {'a': 16, 'b': 28, 'c': 38}, 2: {'a': 7, 'b': 2, 'c': 0}}
{1: {'a': 16, 'b': 28, 'c': 38}, 2: {'a': 7, 'b': 2, 'c': 0}, 3: {'a': 4}}
{1: {'a': 16, 'b': 28, 'c': 38}, 2: {'a': 8, 'b': 10, 'c': 27, 'd': 11}, 3: {'a': 4}}

做这件事最好的方法是什么?

这可能效率很低,但我想到的是:

def dict_add(a, b):
  result = dict(a)

  for key, value in b.items():
    if type(value) != dict:
      result[key] = result.get(key, 0) + value
    else:
      result[key] = dict_add(result.get(key, {}), value)

  return result
运行此代码会导致以下结果:

>>> adict = {1: {'a': 13, 'b': 19, 'c':15}, 2: {'a': 7, 'b': 2, 'c':0}}
>>> bdict = {1: {'a': 3, 'b': 9, 'c': 23}}
>>> 
>>> print dict_add(adict, bdict)
{1: {'a': 16, 'c': 38, 'b': 28}, 2: {'a': 7, 'c': 0, 'b': 2}}

简单递归函数:

>>> adict = {1: {'a': 13, 'b': 19, 'c':15}, 2: {'a': 7, 'b': 2, 'c':0}}
>>> def dict_add(a,b):
...   a = a.copy()
...   for k,v in b.items():
...     if isinstance(v,(dict,)):
...       a[k] = dict_add(a.get(k,{}),v)
...     else:
...       a[k] = a.get(k,0) + v
...   return a
...
>>> dict_add(adict,{1: {'a': 3, 'b': 9, 'c': 23}})
{1: {'a': 16, 'c': 38, 'b': 28}, 2: {'a': 7, 'c': 0, 'b': 2}}
>>> dict_add(dict_add(adict,{1: {'a': 3, 'b': 9, 'c': 23}}),{3:{'a':4}})
{1: {'a': 16, 'c': 38, 'b': 28}, 2: {'a': 7, 'c': 0, 'b': 2}, 3: {'a': 4}}

这是一个功能解决方案。
rec\u add
函数可以根据您的要求使用任意嵌套的词典

def combine(f, d1, d2):
    """Create a new dict combining d1 and d2.

    Keys appearing only in one of the input dict are copied unmodified. Values
    with matching keys are combined using f and copied in the output dict."""

    keys = set(d1.keys() + d2.keys())
    out = { }
    for key in keys:
        if key in d1:
            if key in d2:
                out[key] = f(d1[key], d2[key])
            else:
                out[key] = d1[key]
        else:
            out[key] = d2[key]
    return out

def rec_combine(f, d1, d2):
    """Recursively combine all dicts."""

    def aux(v1, v2):
        if isinstance(v1, (dict,)) and isinstance(v2, (dict,)):
            return rec_combine(f, v1, v2)
        else:
            return f(v1, v2)

    return combine(aux, d1, d2)

def rec_add(d1, d2):
    """Recursively sum values in d1 and d2."""
    return rec_combine(lambda x, y: x + y, d1, d2)

我想是用
+
操作符。@Chris:很遗憾,它不起作用……这个操作嵌套的深度应该有多深?如果adict是
{1:{'a':{'foo':13,'bar':11,…},'b':anotherdict,…}
,该怎么办?请注意:从长远来看,我最终将我的代码转换成了你的代码+meMy页面上的1没有刷新,所以直到我发布了我的解决方案后,我才看到你的解决方案。我们两个答案的接近程度证明了这一点。我认为python最受欢迎的地方之一是思想表达的融合。。。和松散的打字相反,它更像是一种逻辑思维流,真的。不过,我无法想象在C++中这样做。