2 回答
TA贡献1864条经验 获得超2个赞
counter= {'laptop': 5, 'chair':6 , 'tv': 3}
counter1= {'laptop': 2, 'chair': 4, 'tv': 4,'plant':2}
out = [{key : abs(counter1[key] - counter[key])} if ((key in counter) and (key in counter1)) else {key : counter[key]} if (key in counter) else {key:counter1[key]} for key in set(counter.keys() + counter1.keys())]
print out
似乎可以在 1 行中完成,这应该可行。
TA贡献1836条经验 获得超5个赞
用这个
counter= {'laptop': 5, 'chair':6 , 'tv': 3}
counter1= {'laptop': 2, 'chair': 4, 'tv': 4,'plant':2}
out = []
for key, val in counter.items():
if key in counter1:
out.append({key:abs(val-counter1[key])})
else:
out.append({key:val})
for key, val in counter1.items():
if key not in counter:
out.append({key:val})
print(out)
添加回答
举报