I have the following two functions which take two dictionaries and recursively add their values.
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()
)
If I give the following input then the output is fine which I am expecting:
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}}
but if the input is:
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
If there is no key found in the 2nd dictionary it returns key value from first dictionary. So it is operating on one dictionary items, what about the rest of keys in the second dictionary? How can I update the above script so that the output would be:
output: {'abc': {'missing': 1, 'modified': 0, 'additional': 2}, 'cde': {'missing': 1, 'modified': 1, 'additional': 2}}
解决方案
If I understand right what you want to do, all of it could be achieved with the following code:
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) will give the desired result.
Just note that it will raise an AttributeError if called with incompatible types such as
dict_sum({'a': 1}, 2)
Edit to treat lists specially (create list with unique elements).