【发布时间】:2017-11-22 05:49:55
【问题描述】:
我有两个字典,像这样:
d1 = {'red':10, 'blue':20, 'green':30, 'yellow':40}
d2 = {'red':1, 'blue':2, 'green':3}
我想遍历 d1 中的每个项目,看看键是否与 d2 中的键匹配。如果是这样,我想从 d1 键中减去 d2 键,并将新的键/值对移动到新字典中,结果是:
d3 = {'red':9, 'blue':18, 'green':27, 'yellow':40}
我为此编写了以下脚本:
for x, y in d1.items():
for a, b in d2.items():
if x == a:
d3[x] = (y-b)
elif x not in d2.items():
d3[x] = y
这可行,但是当我尝试在包含数千个项目的两个字典上使用它时,该函数永远不会完成。我想这太慢了。
您能推荐一个更好的方法吗?非常感谢。
【问题讨论】:
-
您不需要遍历
d2。您可以在d2中查找x。这就是字典的用途。 -
你能举例说明你的意思吗?我想了解这一点。
标签: python loops dictionary compare