在Python中递归添加字典

时间:2012-01-04 10:09:19

标签: python dictionary

我有以下两个函数,它们使用两个字典并递归地添加它们的值。

def recursive_dict_sum_helper(v1, d2, k):
    try: v2 = d2[k]
    except KeyError: return v1 #problem is here if key not found it just return value but what about rest of the keys which is in d2??

    if not v1: return v2
    # "add" two values: if they can be added with '+', then do so,
    # otherwise expect dictionaries and treat them appropriately.
    try:
        if type(v1) == list and type(v2) == list:
            v1.extend(v2)
            return list(set(v1))
        else:
            return v1 + v2
    except: return recursive_dict_sum(v1, v2)

def recursive_dict_sum(d1, d2):
    if len(d1) < len(d2):
        temp = d1
        d1 = d2
        d2 = temp
    # 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()
    )

如果我提供以下输入,那么输出就可以了,我期待:

a = {'abc': {'missing': 1, 'modified': 0, 'additional': 2}}
b = {'abc': {'missing': 1, 'modified': 1, 'additional': 2}}

mn = recursive_dict_sum(a, b)

output: mn = {'abc': {'missing': 2, 'modified': 1, 'additional': 4}}

但如果输入是:

a = {'abc': {'missing': 1, 'modified': 0, 'additional': 2}}
b = {'cde': {'missing': 1, 'modified': 1, 'additional': 2}}

output: {'abc': {'missing': 1, 'modified': 0, 'additional': 2}} #which is wrong

如果第二个字典中没有找到密钥,则返回第一个字典中的密钥值。所以它在一个字典项上运行,第二个字典中的其余键怎么办?如何更新上面的脚本,以便输出:

output: {'abc': {'missing': 1, 'modified': 0, 'additional': 2}, 'cde': {'missing': 1, 'modified': 1, 'additional': 2}}

2 个答案:

答案 0 :(得分:3)

如果我理解你想做什么,所有这些都可以通过以下代码实现:

def dict_sum(d1, d2):
    if d1 is None: return d2
    if d2 is None: return d1
    if isinstance(d1, list) and isinstance(d2, list):
        return list(set(d1 + d2))
    try:
        return d1 + d2
    except TypeError:
        # assume d1 and d2 are dictionaries
        keys = set(d1.iterkeys()) | set(d2.iterkeys())
        return dict((key, dict_sum(d1.get(key), d2.get(key))) for key in keys)

dict_sum(a, b)会给出所需的结果。

请注意,如果使用不兼容的类型(例如

)调用它会引发AttributeError
dict_sum({'a': 1}, 2)

编辑专门处理列表(使用唯一元素创建列表)。

答案 1 :(得分:2)

制作一个怪物发电机,你似乎喜欢它:)

def recursive_dict_sum(d1, d2):
    return dict((k, ((d1[k] if k in d1 else d2[k])
                       if k not in d1 or k not in d2
                      else (d1[k] + d2[k] if not isinstance(d1[k], dict)
                                        else recursive_dict_sum(d1[k], d2[k]))))
                for k in set(d1.keys() + d2.keys()))