简体   繁体   English

如何从字典中减去值

[英]How to subtract values from dictionaries

I have two dictionaries in Python:我在 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:我想减去字典 d1-d2 之间的值并得到结果:

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 :我认为一种非常 Pythonic 的方式是使用dict comprehension

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

Note that this only works in Python 2.7+ or 3.请注意,这仅适用于 Python 2.7+ 或 3。

Use collections.Counter , iif all resulting values are known to be strictly positive.使用collections.Counter ,如果已知所有结果​​值都是严格的正数。 The syntax is very easy:语法非常简单:

>>> from collections import Counter
>>> d1 = Counter({'a': 10, 'b': 9, 'c': 8, 'd': 7})
>>> d2 = Counter({'a': 1, 'b': 2, 'c': 3, 'e': 2})
>>> d3 = d1 - d2
>>> print d3
Counter({'a': 9, 'b': 7, 'd': 7, 'c': 5})

Mind, if not all values are known to remain strictly positive:请注意,如果不是所有值都已知为严格正值:

  • elements with values that become zero will be omitted in the result结果中将省略值为零的元素
  • elements with values that become negative will be missing, or replaced with wrong values.值变为负的元素将丢失,或替换为错误的值。 Eg, print(d2-d1) can yield Counter({'e': 2}) .例如, print(d2-d1)可以产生Counter({'e': 2})

Just an update to Haidro answer.只是对 Haidro 答案的更新。

Recommended to use subtract method instead of "-".建议使用减法而不是“-”。

d1.subtract(d2) d1.subtract(d2)

When - is used, only positive counters are updated into dictionary.使用 - 时,仅将正计数器更新到字典中。 See examples below请参阅下面的示例

c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
a = c-d
print(a)        # --> Counter({'a': 3})
c.subtract(d)
print(c)        # --> Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

Please note the dictionary is updated when subtract method is used.请注意,当使用减法方法时,字典会更新。

And finally use dict(c) to get Dictionary from Counter object最后使用 dict(c) 从 Counter 对象中获取 Dictionary

Haidro posted an easy solution, but even without collections you only need one loop: Haidro 发布了一个简单的解决方案,但即使没有collections您也只需要一个循环:

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

for k, v in d1.items():
    d3[k] = v - d2.get(k, 0) # returns value if k exists in d2, otherwise 0

print(d3) # {'c': 5, 'b': 7, 'a': 9, 'd': 7}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM