为什么这个字典值都是一样的?

Why this dictionary values are all the same?

我正在尝试编写这个字典理解,但我不知道为什么所有的字典值都相同。

密码是:

from string import ascii_uppercase

dictionary = {key: value for key in range(0, len(ascii_uppercase)) for value in ascii_uppercase}

结果是:

{0: 'Z', 1: 'Z', 2: 'Z', 3: 'Z', 4: 'Z', 5: 'Z', 6: 'Z', 7: 'Z', 8: 'Z', 9: 'Z', 10: 'Z', 11: 'Z', 12: 'Z', 13: 'Z', 14: 'Z', 15: 'Z', 16: 'Z', 17: 'Z', 18: 'Z', 19: 'Z', 20: 'Z', 21: 'Z', 22: 'Z', 23: 'Z', 24: 'Z', 25: 'Z'}

为什么它只给我字符串的最后一个字符作为所有值? 我该如何解决?

因为内循环总是以列表结尾结束,因此最好使用 enumerate()dict()

dictionary = dict(enumerate(ascii_uppercase))

第二个 for 循环在第一个 for 循环之前完全执行,因此它弄乱了结果。您可以只使用一个 for 循环来尝试这种方法:

dictionary = {i: ascii_uppercase[i] for i in range(len(ascii_uppercase))}

将您的代码更改为此

from string import ascii_uppercase

dictionary = {key: value for key,value in enumerate(ascii_uppercase, 0)}

输出

{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J', 10: 'K', 11: 'L', 12: 'M', 13: 'N', 14: 'O', 15: 'P', 16: 'Q', 17: 'R', 18: 'S', 19: 'T', 20: 'U', 21: 'V', 22: 'W', 23: 'X', 24: 'Y', 25: 'Z'}

虽然还有其他合适的答案,但我相信这就是您认为正在做的事情。

from string import ascii_uppercase


{key: value for key,value in zip(range(0, len(ascii_uppercase)),ascii_uppercase)}

如果将字典理解转换为常规循环,则会得到:

dictionary = {}
for key in range(0, len(ascii_uppercase)): # for every number in range 0-26
    for value in ascii_uppercase:          # for every letter in range a-z
        dictionary[key] = value            # d[num] = letter

每个数字的最后一个字母是 'z',因此您的字典会在每个数字的内部循环结束时用它更新。

你可以试试:

di = {}
for i, letter in enumerate(ascii_uppercase):
    di[i] = letter

di = {i: letter for i, letter in enumerate(ascii_uppercase)}

di = dict(enumerate(ascii_uppercase))