python字典之间进行加减运算
目录
python字典之间进行加减运算
python字典之间的相加减,其实就是 合并两个字典 。
相加的时候对相同键对应值相加,不同键的项就整合到一起;相减的时候对相同键对应值相减(结果会忽略掉值为0和小于0的项),不同键的项就只保留“被减数”的项。
python字典之间是不能直接进行加减运算 ,否则会报错。如:
x = {'a': 1, 'b': 5, 'c': 7}
y = {'b': 2, 'c': 8, 'd': 20}
print(x + y)
print(x - y)
执行后报TypeError:
TypeError: unsupported operand type(s) for +: ‘dict’ and ‘dict’
TypeError: unsupported operand type(s) for - : ‘dict’ and ‘dict’
所以需要借助 collections.Counter 模块来实现字典的相加减。如:
from collections import Counter
x = {'a': 1, 'b': 5, 'c': 7}
y = {'b': 2, 'c': 8, 'd': 20}
print(dict(Counter(x)+Counter(y)))
print(dict(Counter(x)-Counter(y)))
执行结果:
注:可见相减后 键‘c’ 和 键‘d’的项都被忽略掉了。