gpt4 book ai didi

python - 如何合并嵌套字典?

转载 作者:行者123 更新时间:2023-12-01 23:08:44 25 4
gpt4 key购买 nike

我有一个嵌套字典列表(python 3.9),看起来像这样:

records = [
{'Total:': {'Owner:': {'Available:': {'15 to 34 years': 1242}}}},
{'Total:': {'Owner:': {'Available:': {'35 to 64 years': 5699}}}},
{'Total:': {'Owner:': {'Available:': {'65 years and over': 2098}}}},
{'Total:': {'Owner:': {'No Service:': {'15 to 34 years': 43}}}},
{'Total:': {'Owner:': {'No Service:': {'35 to 64 years': 64}}}},
{'Total:': {'Owner:': {'No Service:': {'65 years and over': 5}}}},
{'Total:': {'Renter:': {'Available:': {'15 to 34 years': 1403}}}},
{'Total:': {'Renter:': {'Available:': {'35 to 64 years': 2059}}}},
{'Total:': {'Renter:': {'Available:': {'65 years and over': 395}}}},
{'Total:': {'Renter:': {'No Service:': {'15 to 34 years': 16}}}},
{'Total:': {'Renter:': {'No Service:': {'35 to 64 years': 24}}}},
{'Total:': {'Renter:': {'No Service:': {'65 years and over': 0}}}},
]

嵌套层次并不总是一致的。上面的示例有 4 个级别(总计、所有者/承租人、可用/无服务、年龄段),但有些示例只有一个级别,而其他示例则有多达 5 个级别。

我想以一种不会像 update(){*dict_a, **dict_b} 那样替换最终字典的方式合并数据。

最终输出应该是这样的:

combined = {
'Total': {
'Owner': {
'Available': {
'15 to 34 years': 1242,
'35 to 64 years': 5699,
'65 years and over': 2098
},
'No Service:': {
'15 to 34 years': 43,
'35 to 64 years': 64,
'65 years and over': 5
}
},
'Renter': {
'Available': {
'15 to 34 years': 1403,
'35 to 64 years': 2059,
'65 years and over': 395
},
'No Service:': {
'15 to 34 years': 16,
'35 to 64 years': 24,
'65 years and over': 0
}
},
}
}

最佳答案

递归是一种在任意嵌套结构上导航和操作的简单方法:

def combine_into(d: dict, combined: dict) -> None:
for k, v in d.items():
if isinstance(v, dict):
combine_into(v, combined.setdefault(k, {}))
else:
combined[k] = v

combined = {}
for record in records:
combine_into(record, combined)
print(combined)
{'Total:': {'Owner:': {'Available:': {'15 to 34 years': 1242, '35 to 64 years': 5699, '65 years and over': 2098}, 'No Service:': {'15 to 34 years': 43, '35 to 64 years': 64, '65 years and over': 5}}, 'Renter:': {'Available:': {'15 to 34 years': 1403, '35 to 64 years': 2059, '65 years and over': 395}, 'No Service:': {'15 to 34 years': 16, '35 to 64 years': 24, '65 years and over': 0}}}}

这里的一般想法是,每次调用 combine_into 都会获取一个字典并将其组合到 combined 字典中——每个本身就是字典的值都会导致另一个递归调用,而其他值只是按原样复制到 combined 中。

请注意,如果某些 records 对特定节点是否为叶子存在分歧,这将引发异常(或破坏某些数据)!

关于python - 如何合并嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70310388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com