How to subtract values from dictionaries

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

    I think a very Pythonic way would be using 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.

提交回复
热议问题