Python 如何从字典中减去值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17671875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:51:42  来源:igfitidea点击:

How to subtract values from dictionaries

pythondictionary

提问by Colargol

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()):

采纳答案by Erfa

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。

回答by TerryA

Use collections.Counter, iif all resulting values are known to be strictly positive. The syntax is very easy:

collections.Counter如果已知所有结果​​值都严格为正,则使用, 。语法非常简单:

>>> 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 strictlypositive:

请注意,如果不是所有值都已知为严格正值:

  • 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. E.g., print(d2-d1)can yield Counter({'e': 2}).
  • 结果中将省略值为零的元素
  • 值变为负的元素将丢失,或替换为错误的值。例如,print(d2-d1)可以 yield Counter({'e': 2})

回答by joente

Haidro posted an easy solution, but even without collectionsyou 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}

回答by Hemanth

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