python3 多个多层 dict 合并

2020-12-07 21:02:44 +08:00
 lanceadd

各位老哥我想问下在 python3 中,我有两个多层 dict,怎么合并他们 例如这种,谢谢老哥们

{
	user_id:{
    	title_id:{
        	relation_id:{
            	reviewer_id:rate
            }
        }
    }
}
1041 次点击
所在节点    问与答
5 条回复
renmu123
2020-12-07 21:14:41 +08:00
不知道你所谓的合并两个 dict 是什么操作,你给了个例子(例子也不完整),但是没有给出应该呈现的结果
westoy
2020-12-07 21:15:31 +08:00
你给案例别给一半啊.....
lanceadd
2020-12-07 22:19:47 +08:00
@renmu123 @westoy 抱歉抱歉我也不知道为啥会缺了一块, 发布前预览是没问题的, 另外一个 dict 也是这个,但是 user_id,title_id 这些 key 可能不相同,然后可能层级也不一样,可能会只有两层那种,然后想把一个 dict,update 到另外一个 dict 上,如果那一层的 key 相同 value 不同就合并上去,举个例子按照我上面那个结构,user_id 、title_id 相同但是 relation_id 不同,怎么把它俩合并起来,我原本以为 dict.update()就好了,但是发现对多层的 dict 直接 update 会直接覆盖,然后发现只能一层一层的 update,就很尴尬,除了递归还有啥办法可以更新不同深度的嵌套字典的值吗
lanceadd
2020-12-07 22:47:25 +08:00
多个嵌套字典合并为一个
lanceadd
2020-12-08 09:47:04 +08:00
解决了
```
def recursive_update(
default: dict,
custom: dict
):
"""
递归更新 dict
:param default:
:param custom:
:return:
"""
if not isinstance(default, dict) or not isinstance(custom, dict):
raise TypeError('Params of recursive_update should be dicts')

for key in custom:
if isinstance(custom[key], dict) and isinstance(default.get(key), dict):
default[key] = recursive_update(default[key], custom[key])
else:
default[key] = custom[key]

return default
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/733098

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX