for循环中的Python最后一项不能添加到字典中

2024-10-04 11:32:41 发布

您现在位置:Python中文网/ 问答频道 /正文

letters = ['a', 'b', 'c', 'd', 'e', 'f']
numbers = ['judge1','judge2','judge3','judge4','judge5']
dictionary = {}
for letter in letters:
    for number in numbers:
        roundDictionary[letter] = {number : None}

我希望字典是:

dictionary = {'a' : {'1' : None, '2' : None, '3' : None, '4' : None, '5' : 
None}} 

以此类推,但字典仅显示列表最后一个位置的项,如下所示:

{'a': {'5': None}, 'b': {'5': None}, 'c': {'5': None}, 'd': {'5': None}, 'e': {'5': None}, 'f': {'5': None}}

我怎样才能把所有的数字都加到字典里呢?谢谢


Tags: innonenumberfordictionary字典numbersletter
1条回答
网友
1楼 · 发布于 2024-10-04 11:32:41

问题是您正在将值重新分配给每个循环中的键。实际上,每次都会覆盖它,这就是为什么只看到最后一个值。试试这个

letters = ['a', 'b', 'c', 'd', 'e']
numbers = [1, 2, 3, 4, 5]
dictionary = {}

for letter in letters:
    for number in numbers:
        if (letter not in dictionary):
            dictionary[letter] = {}
        dictionary[letter][number] = None

编辑:来自@Joran Beasley的评论是在发布这篇文章时出现的。他的方法比使用嵌套循环和检查键是否存在要干净得多

相关问题 更多 >