How to subtract values from dictionaries

前端 未结 4 1638
执笔经年
执笔经年 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:12

    Just an update to Haidro answer.

    Recommended to use subtract method instead of "-".

    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

提交回复
热议问题