使用相同的键合并两个字典,但将其添加为另一个值(而不是替换) [英] Merge two dicts with the same keys but add as another value (not replace)
本文介绍了使用相同的键合并两个字典,但将其添加为另一个值(而不是替换)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此似乎显示了一个附加到数组而不向字典添加另一个值的示例
This seems to shown an example of appending to an array, not adding another value to a dict.
dict_1 = {a:{价格:4000},b:{价格:14000}}
dict_2 = {a:{折扣:0100},b:{折扣:0400}}
我想将它们合并为:
merged_dict: { a: {
price: 4000,
discount: 0100
},
b: {
price: 14000,
discount: 0400
}
}
如何实现?两个字典将始终具有相同的键.
How to achieve that? Both dictionaries will always have the same keys.
推荐答案
字典理解将解决此问题(我从问题中正确格式化了字典定义,并使用Python 3.8.0进行了测试):
A dictionary comprehension will solve this (I correctly formatted your dictionary definitions from the question, tested with Python 3.8.0):
>>> dict_1 = {'a': {'price': 4000}, 'b': {'price': 14000} }
>>> dict_2 = {'a': {'discount': 100}, 'b': {'discount': 400} }
>>> merged_dict = {k: { **dict_1[k], **dict_2[k] } for k in dict_2.keys()}
>>> merged_dict
{'a': {'price': 4000, 'discount': 100}, 'b': {'price': 14000, 'discount': 400}}
这篇关于使用相同的键合并两个字典,但将其添加为另一个值(而不是替换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文