How to subtract values from dictionaries

前端 未结 4 1641
执笔经年
执笔经年 2020-12-15 05:43

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 s

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 06:10

    Use collections.Counter, iif all resulting values are known to be strictly positive. 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. E.g., print(d2-d1) can yield Counter({'e': 2}).

提交回复
热议问题