Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 合并dict数组中的重复项_Python_Arrays_Recursion_Dictionary_Merge - Fatal编程技术网

Python 合并dict数组中的重复项

Python 合并dict数组中的重复项,python,arrays,recursion,dictionary,merge,Python,Arrays,Recursion,Dictionary,Merge,我正在努力解决递归合并问题 假设我有: a=[{'name':"bob", 'age':10, 'email':"bob@bla", 'profile':{'id':1, 'role':"admin"}}, {'name':"bob", 'age':10, 'email':"other mail", 'profile':{'id':2, 'role':"dba"}, 'home':"/home/bob" }] 我需

我正在努力解决递归合并问题

假设我有:

a=[{'name':"bob", 
    'age':10, 
    'email':"bob@bla", 
    'profile':{'id':1, 'role':"admin"}}, 
   {'name':"bob", 
    'age':10, 
    'email':"other mail", 
    'profile':{'id':2, 'role':"dba"},
    'home':"/home/bob"
  }]
我需要一些东西来递归合并条目。如果同一级别上现有给定键的值不同,则会将该值附加到数组中

b = merge(a)
print b
{'name':"bob", 
 'age':10, 
 'email':["bob@bla","other mail"], 
 'profile':{'id':[1,2], 'role'=["admin", "dba"], 'home':"/home/bob"}
我写了这段代码:

def merge(items):
    merged = {}
    for item in items:
        for key in item.keys():
            if key in merged.keys():
                if item[key] != merged[key]:
                    if not isinstance(merged[key], list):
                        merged[key] = [merged[key]]
                    if item[key] not in merged[key]:
                        merged[key].append(item[key])
            else:
                merged[key] = item[key]
    return merged 
输出为:

{'age': 10,
 'email': ['bob@bla', 'other mail'],
 'home': '/home/bob',
 'name': 'bob',
 'profile': [{'id': 1, 'role': 'admin'}, {'id': 2, 'role': 'dba'}]}
这不是我想要的

我不知道如何处理递归


谢谢:)

当您遍历参数中的每个字典,然后遍历每个字典中的每个键和值时,您需要以下规则:

  • 如果输出中没有与该键对应的内容,则将新键和值添加到输出中
  • 如果该键有一个值,并且与新值相同,则不执行任何操作
  • 如果该键有一个值,并且是一个列表,
    将新值附加到列表中
    
  • 如果该键有一个值,并且是一个字典,则递归地将新值与现有字典合并
  • 如果该键有一个值,并且它既不是列表也不是字典,则将输出中的值设置为当前值和新值的列表
  • 代码:

    def merge(*dicts):
        """Recursively merge the argument dictionaries."""
        out = {}
        for dct in dicts:
            for key, val in dct.items():
                try:
                    out[key].append(val) # 3.
                except AttributeError:
                    if out[key] == val:
                        pass # 2.
                    elif isinstance(out[key], dict):
                        out[key] = merge(out[key], val) # 4.
                    else:
                        out[key] = [out[key], val] # 5.
                except KeyError:
                    out[key] = val # 1.
        return out
    
    使用中:

    >>> import pprint
    >>> pprint.pprint(merge(*a))
    {'age': 10,
     'email': ['bob@bla', 'other mail'],
     'home': '/home/bob',
     'name': 'bob',
     'profile': {'id': [1, 2], 'role': ['admin', 'dba']}}
    

    你的代码在哪里?它到底有什么问题?正如我说的,我正在努力解决这个问题…所以你有。。。没有什么?这不是一个代码编写服务。其他几个主题也没有提供任何代码,我正在自己做一些事情,如果我能让它工作,我会发布它。。。我在寻求建议。