如何从字典中减去值 [英] How to subtract values from dictionaries

查看:111
本文介绍了如何从字典中减去值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中有两个字典:

  d1 = {'a':10,'b':9, c':8,'d':7} 
d2 = {'a':1,'b':2,'c':3,'e':2}

我想在字典d1-d2之间减去值,并得到结果:

  d3 = {'a':9,'b':7,'c':5,'d':7} 
pre>

现在我使用两个循环,但这个解决方案不是太快了

  for x,i in enumerate(d2.keys()):
for y,j in enumerate(d1.keys()):


解决方案

我认为非常Pythonic的方式将使用 dict comprehension

  d3 = {key:d1 [key] d2.get(key,0)for d1.keys()} 

请注意,这只是在Python 2.7+或3中使用。


I have two dictionaries in Python:

d1 = {'a': 10, 'b': 9, 'c': 8, 'd': 7}
d2 = {'a': 1, 'b': 2, 'c': 3, 'e': 2}

I want to substract values between dictionaries d1-d2 and get the result:

d3 = {'a': 9, 'b': 7, 'c': 5, 'd': 7 }

Now I'm using two loops but this solution is not too fast

for x,i in enumerate(d2.keys()):
        for y,j in enumerate(d1.keys()):

解决方案

I think a very Pythonic way would be using dict comprehension:

d3 = {key: d1[key] - d2.get(key, 0) for key in d1.keys()}

Note that this only works in Python 2.7+ or 3.

这篇关于如何从字典中减去值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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