我正在使用这个字典推导式dict2={key:a[key]-b.get(key,0) for key in a}但是没有得到想要的输出
a={'x'=3,'y'=4}
b={'x'=1,'y'=2,'z'=3}
c=a-b
desired output={'x'=2,'y'=2,'z'=-3}
试试这个
keys=list(a)
keys.extend(x for x in b if x not in a)
dict2={key:a.get(key,0)-b.get(key,0) for key in keys}
或一行程序
dict2 = {key:a.get(key,0)-b.get(key,0) for key in list(a) + [x for x in b if x not in a]}
a = {'x': 3, 'y': 4}
a.setdefault('z', 0)
b = {'x': 1, 'y': 2, 'z': 3}
desired_output = {k1: v1 - v2 for k1, v1 in a.items() for k2, v2 in b.items() if k1 == k2}
输出:
{'x': 2, 'y': 2, 'z': -3}
编辑:如果您不知道丢失了哪些键:
for k1, v1 in b.items():
if not k1 in a.keys():
a.setdefault(k1, 0)