在Python中递归添加字典 [英] Adding dictionaries recursively in Python

查看:327
本文介绍了在Python中递归添加字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个函数需要两个字典并递归添加它们的值。

  def recursive_dict_sum_helper(v1,d2, k):
try:v2 = d2 [k]
除了KeyError:return v1 #problem在这里如果键没有找到它只是返回值,但是其余的键在d2?

如果不是v1:return v2
#添加两个值:如果他们可以添加+,那么这样做,
#否则预期字典并对待适当。
try:
if type(v1)== list and type(v2)== list:
v1.extend(v2)
return list(set(v1))
else:
return v1 + v2
除了:return recursive_dict_sum(v1,v2)

def recursive_dict_sum(d1,d2):
if len(d1 ) len(d2):
temp = d1
d1 = d2
d2 = temp
#为每个
#原始键值递归生成新的键值对配对,并做出结果的dict。
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)

输出: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}}#这是错误的

如果在第二个字典中找不到键,则返回密钥va从第一个字典那么它是在一个字典项目上运行的,第二个字典中其他的键呢?如何更新上述脚本,以便输出为:

 输出:{'abc':{'missing' 1,'modified':0,'additional':2},'cde':{'missing':1,'modified':1,'additional':2}} 


解决方案

如果我明白你想要做什么,所有这一切都可以通过以下代码实现: / p>

  def dict_sum(d1,d2):
如果d1为无:返回d2
如果d2为无:return d1
if isinstance(d1,list)and isinstance(d2,list):
return list(set(d1 + d2))
try:
return d1 + d2
除了TypeError:
#假设d1和d2是字典
keys = set(d1.iterkeys())| set(d2.iterkeys())
返回dict((key,dict_sum(d1.get(key),d2.get(key)))键$)

dict_sum(a,b)将给出所需的结果。



请注意,如果使用不兼容类型(例如

)调用 AttributeError pre> dict_sum({'a':1},2)

编辑特别处理列表(创建具有唯一元素的列表)。


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).

这篇关于在Python中递归添加字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆