如何将一个字典中的元素添加到其他字典?蟒蛇

时间:2011-11-01 07:43:37

标签: python dictionary

我有主词典。

mainDict = {'count': 10, 'a': {'abc': {'additional': 0, 'missing': 0, 'changed': 0}}}

现在我的新词典与mainDict中的键相同,将此词典称为b,具有不同的值。

b = {'count': 20, 'a': {'abc': {'additional': 10, 'missing': 10, 'changed': 10}}}

我想更新(添加操作)主词典中的键值,所以我这样做..

mainDict = {'count': mainDict['count'] + b['count'], 'a': }

我坚持更新key a的值。如果我使用mainDict.update(b),那么它将替换以前的值。任何有效的解决方案??

所需的最终输出是:

mainDict = {'count': 30, 'a': {'abc': {'additional': 10, 'missing': 10, 'changed': 10}}}

由于

2 个答案:

答案 0 :(得分:3)

def recursive_dict_sum_helper(v1, v2):
    # "add" two values: if they can be added with '+', then do so,
    # otherwise expect dictionaries and treat them appropriately.
    try: return v1 + v2
    except: return recursive_dict_sum(v1, v2)

def recursive_dict_sum(d1, d2):
    # Recursively produce the new key-value pair for each
    # original key-value pair, and make a dict with the results.
    return dict(
        (k, recursive_dict_sum_helper(v, d2[k]))
        for (k, v) in d1.items()
    )

mainDict = recursive_dict_sum(mainDict, b)

答案 1 :(得分:1)

我写道:

def sum_dicts_recursive(d1, d2):
    for k, v1 in d1.items():
        if isinstance(v1, dict):
            yield (k, dict(process(v1, d2[k])))
        else:
            yield (k, v1 + d2[k])

result = dict(sum_dicts_recursive(mainDict, b))
# {'count': 30, 'a': {'abc': {'changed': 10, 'additional': 10, 'missing': 10}}}

请注意sum_dicts_recursive可以作为单行生成器表达式写入,但这可能更难理解。