How to subtract values from dictionaries

前端 未结 4 1640
执笔经年
执笔经年 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 05:59

    Haidro posted an easy solution, but even without collections you only need one loop:

    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}
    

提交回复
热议问题