我有以下两个函数,它们接受两个字典并递归地添加它们的值。
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}}
最佳答案
如果我理解正确你想做什么,所有这一切都可以通过以下代码实现:
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)
编辑以特殊处理列表(创建具有独特元素的列表)。
关于python - 在 Python 中递归添加字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8725060/