【问题标题】:Can someone explain how this loops through a dictionary?有人可以解释一下这是如何通过字典循环的吗?
【发布时间】:2019-03-27 01:27:06
【问题描述】:

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

一切正常,我只是不明白它为什么起作用或在做什么。

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 字典的。

【问题讨论】:

  • 这叫“字典理解”,查一下。也不要使用变量名,例如dictlist,因为它们会掩盖内置名称。
  • dict 是内置的,您不应该将其用作变量。

标签: python dictionary


【解决方案1】:

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

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

为了生成这样的字典,他们使用“字典理解”,非常高效。

现在,这个结构:

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

可以改写为:

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

您可以将x[k] 替换为上面的v

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多