Adding Dictionaries Recursively In Python
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:
Solution 1:
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).
Solution 2:
Made in one monster-generator as you seem to like it :)
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()))
Post a Comment for "Adding Dictionaries Recursively In Python"