python - 使用 for/in 语句合并字典功能
问题描述
我是 Python 的初学者,所以我需要一个简单的解释。
我有两个字典:
supply_dictionarie = {'Apple': 20, 'Cigar': 100, 'Milk': 210, 'Flower': 75}
goods_dictionarie = {'Milk': 210, 'Apple': 50, 'WhiteWine': 200, 'Beer': 300, 'Oranges': 400}
我试图合并这两个字典,同时对重复键的值求和。我的目的是获得:
merged_dictionarie = {'Milk': 420, 'Cigar': 100, 'Apple': 70, 'WhiteWine': 200, 'Beer': 300, 'Oranges': 400, 'Flower': 75} *(not necessarily in this order)
我正在使用以下代码:
def merge_supply():
for k in supply_dictionarie:
if k in set(goods_dictionarie):
merged_dictionarie[k] = goods_dictionarie.get(k, 0) + supply_dictionarie.get(k, 0)
elif k not in set(goods_dictionarie):
merged_dictionarie[k] = supply_dictionarie.get(k, 0)
else:
break
for k in goods_dictionarie:
if k not in set(supply_dictionarie):
merged_dictionarie[k] = goods_dictionarie.get(k, 0)
else:
break
但我得到的只是:
merged_dictionarie = {'Apple': 70, 'Cigar': 100, 'Milk': 420, 'Flower': 75}
对我来说,这表明第二个“for/in”表达式没有成功执行工作。出了什么问题?
解决方案
您可以使用以下方法简化循环:
>>> from collections import defaultdict
>>> merged = defaultdict(int)
>>> for i in supply_dictionarie :
... merged[i] += supply_dictionarie[i]
...
>>> for i in goods_dictionarie :
... merged[i] += goods_dictionarie[i]
...
>>> dict(merged)
{'Beer': 300, 'Flower': 75, 'Apple': 70, 'Cigar': 100, 'WhiteWine': 200, 'Oranges': 400, 'Milk': 420}
推荐阅读
- ssis - 为什么 DT_WSTR 与 ssis 模糊分组的 nvarchar 数据类型不匹配
- jquery - Jquery 帮助:基于多个下拉选择显示/隐藏“添加到购物车”div
- javascript - Angular2:将组件附加到正文会消除您通过 ComponentRef 销毁它的能力
- ruby-on-rails - Rails 5:当多态引用也带有不同的关联时如何允许模型创建
- java - 如何在计算矩阵和时提高性能
- reactjs - 在 setState 之后,react 中的输入搜索为空
- nginx - 在特定数量的请求后在 Varnish-Cache 中缓存资源
- awk - 如何在同一行上 gsed 子字符串的多个实例
- mailchimp - mailchimp 观众没有更新
- javascript - Javascript IF 语句可以处理两个以上的条件吗?