gpt4 book ai didi

Python 深度合并字典数据

转载 作者:IT老高 更新时间:2023-10-28 20:51:50 25 4
gpt4 key购买 nike

是否有 Python 中的库可用于深度合并字典:

以下内容:

a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }

当我合并时,我希望它看起来像:

a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }

最佳答案

我希望我不要重新发明轮子,但解决方案相当短。而且,编写代码非常有趣。

def merge(source, destination):
"""
run me with nosetests --with-doctest file.py

>>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
>>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }
>>> merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }
True
"""
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
merge(value, node)
else:
destination[key] = value

return destination

所以想法是将源复制到目标,并且每次它是源中的dict时,递归。因此,如果在 A 中给定元素包含 dict 而在 B 中包含任何其他类型,那么您确实会遇到错误。

[EDIT] 正如评论中所说,解决方案已经在这里:https://stackoverflow.com/a/7205107/34871

关于Python 深度合并字典数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20656135/

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