python递加_在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: 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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值