更新python词典而不覆盖子词典的通用方法 [英] Generic way of updating python dictionary without overwriting the subdictionaries

查看:43
本文介绍了更新python词典而不覆盖子词典的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何通用方法可以更新python字典而不覆盖子字典.词典是动态生成的,因此无法预先预测级别,深度或子键.

Is there any generic way to update python dictionary without overwriting the sub-dicts. The dictionaries are dynamically generated hence, cannot predict the level, depth or subkeys in advance.

考虑以下两个字典是动态生成的-

Consider following two dictionaries are generated dynamically -

d1 = {'a' : { 'b' : 'c'} }
d2 = {'a' : { 'd' : 'e'} }

如果我调用更新函数,结果将是这样的d1.update(d2)打印d1

If I call an update function the result would be something like this d1.update(d2) print d1

结果=

{'a': {'d': 'e'}}

预期结果=

{'a': {'b': 'c', 'd': 'e'}}

以上词典仅作为示例.字典可以是动态生成的任何级别.因此,请提供python ..或其他方式的内置函数.

Above dictionaries are just for an example. The dictionaries could be of any level dynamically generated. Hence, provide if any in built function for python.. or some other way.

推荐答案

AFAIK没有内置的功能.您可以尝试这样的事情:

AFAIK there is no built-in for this. You can try something like this:

result = {key : [value, d2[key]] if key in d2 else value 
          for key,value in d1.items()}

假设您要使用字典作为结果(问题中的预期结果不是有效的Python构造).

Assuming you want a dictionary as a result (expected result in your question is not a valid Python construct).

或者:

result = {key : [value, d2[key]] if key in d2 else [value]
          for key,value in d1.items()}

如果您希望始终有一个列表作为值.

if you want to always have a list as a value.

要合并嵌套的字典,您可以使用以下单行代码:

To merge nested dicts you can use this one-liner:

result = {key : value.update(d2[key]) or value if key in d2 else value
          for key,value in d1.items()}

这篇关于更新python词典而不覆盖子词典的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆