关于python:有人可以解释这是如何通过字典循环的吗?

Can someone explain how this loops through a dictionary?

我有两本字典,我想比较一下它们,看看它们之间有什么不同。我感到困惑的是dict。这个有名字吗?

一切都很好,我只是不太明白它为什么起作用,它在做什么。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
x = {"#04": 0,"#05": 0,"#07": 0,"#08": 1,"#09": 0,"#10": 0,"#11": 1,"#12": 1,"#14": 1,"#15": 1,"#17": 0,"#18": 1,"#19": 1,"#20": 1}

y = {"#04": 1,"#05": 0,"#07": 0,"#08": 1,"#09": 0,"#10": 0,"#11": 1,"#12": 1,"#14": 1,"#15": 0,"#17": 1,"#18": 1,"#19": 0,"#20": 1}

dict = {k: x[k] for k in x if y[k] != x[k]}

list = []

for k, v in dict.items()
  if v==0:
    difference = k + ' became ' + '0'
    list.append(difference)
  else:
    difference = k + ' became ' + '1'
    list.append(difference)

print(list)

它应该打印['#04 became 0', '#15 became 1', '#17 became 0', '#19 became 1'],但我不明白dict是如何工作的,以便循环使用x和y字典的。


实现的过程是比较两个字典,假设它们都有相同的键(可能y可能有更多的条目)。

为了快速进行比较并方便下一个代码块,他们决定生成一个只包含具有不同值的键的字典。

为了生成这样的词典,他们使用"词典理解",这是非常有效的。

现在,这个结构:

1
d = {k: x[k] for k in x if y[k] != x[k]}

可重写为:

1
2
3
4
d = {}
for k,v in x:          # for each key->value pairs in dictionary x
    if y[k] != x[k]:   # if the corresponding elements are different
        d[k] = x[k]    # store the key->value pair in the new dictionary

你可以用上面的v替换x[k]