我想做一个通用函数来合并python中的n个嵌套字典.

我创建了一个函数来合并三个字典,但我想将其推广到n个嵌套字典.

我创建的功能是:

def mergedicts(dict1, dict2, dict3):
for k in set(dict1.keys()).union(dict2.keys()).union(dict3.keys()):
    if k in dict1 and k in dict2 and k in dict3 :
        if isinstance(dict1[k], dict) and isinstance(dict2[k], dict) and isinstance(dict3[k], dict):
            yield (k, dict(mergedicts(dict1[k], dict2[k], dict3[k])))
        else:
            # If one of the values is not a dict, you can't continue merging it.
            # Value from first and second dict are written in form of lists.
            yield (k, [dict1[k],dict2[k], dict3[k]])
            # Alternatively, replace this with exception raiser to alert you of value conflicts
    elif k in dict1:
        yield (k, dict1[k])
    elif k in dict2:
      yield(k,dict2[k])
    else:
        yield (k, dict3[k]

dict1 = {"canada":{'america':189,'asia':175,'europe': 186},
     "norway":{'australia': 123,'africa':124,'brazil':125}}
dict2=  {"canada":{'america':13,'asia':14,'europe': 15},
     "norway":{'australia': 17,'africa':18,'brazil':19}}
dict3=  {"canada":{'america':127,'asia':256,'europe': 16},
     "norway":{'australia': 17,'africa':18,'brazil':19}}
# After running the above function I have got this output
{'canada': {'europe': [186, 15, 16], 'america': [189, 13, 127], 'asia': [175, 14, 256]}, 'norway': {'australia': [123, 17, 17], 'brazil': [125, 19, 19], 'africa': [124, 18, 18]}}

Is there any way to generalize the function so that I could merge n nested dictionaries in Python. (e.g. I may want to merge 20 nested dictionaries in python in a manner similar to the above, but my approach only allows for merging three nested dictionaries.)

推荐答案

可以使用嵌套的for循环来生成所需的输出.

使用两种词典理解创建词典 struct .然后,使用for个循环在嵌套字典中建立列表值:

data = [dict1, dict2, dict3]

result = {k: {ik: [] for ik in dict1[k].keys()} for k in dict1.keys()}

for entry in data:
    for key, value in entry.items():
        for inner_key, inner_value in value.items():
            result[key][inner_key].append(inner_value)
            
print(result)

这将产生:

{
'canada': {
  'america': [189, 13, 127],
  'asia': [175, 14, 256],
  'europe': [186, 15, 16]
 },
'norway': {
  'australia': [123, 17, 17],
  'africa': [124, 18, 18],
  'brazil': [125, 19, 19]
 }
}

Python相关问答推荐

隐藏QComboBox的指示器(qdarkstyle)

合并其中一个具有重叠范围的两个框架的最佳方法是什么?

Docker-compose:为不同项目创建相同的容器

如何在Python中增量更新DF

pandas DataFrame中类型转换混乱

过载功能是否包含Support Int而不是Support Int?

Pydantic:如何将对象列表表示为dict(将列表序列化为dict)

如何销毁框架并使其在tkinter中看起来像以前的样子?

在Python中为变量的缺失值创建虚拟值

对Numpy函数进行载体化

Python库:可选地支持numpy类型,而不依赖于numpy

log 1 p numpy的意外行为

基于索引值的Pandas DataFrame条件填充

关于Python异步编程的问题和使用await/await def关键字

UNIQUE约束失败:customuser. username

在Python 3中,如何让客户端打开一个套接字到服务器,发送一行JSON编码的数据,读回一行JSON编码的数据,然后继续?

在Python中使用if else或使用regex将二进制数据如111转换为001""

在Python中使用yaml渲染(多行字符串)

Gekko中基于时间的间隔约束

BeautifulSoup-Screper有时运行得很好,很健壮--但有时它失败了::可能这里需要一些更多的异常处理?