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:
defdict_sum(d1, d2):
if d1 isNone: return d2
if d2 isNone: return d1
ifisinstance(d1, list) andisinstance(d2, list):
returnlist(set(d1 + d2))
try:
return d1 + d2
except TypeError:
# assume d1 and d2 are dictionaries
keys = set(d1.iterkeys()) | set(d2.iterkeys())
returndict((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 :)
defrecursive_dict_sum(d1, d2):
returndict((k, ((d1[k] if k in d1 else d2[k])
if k notin d1 or k notin d2
else (d1[k] + d2[k] ifnotisinstance(d1[k], dict)
else recursive_dict_sum(d1[k], d2[k]))))
for k inset(d1.keys() + d2.keys()))
Post a Comment for "Adding Dictionaries Recursively In Python"