我正在尝试使用 for 循环创建字典。我有一个有序列表,我正在尝试将列表中的值与有序数字相匹配。例如: {0:100, 1:423, 2:434}
我在创建 for 循环时遇到了麻烦。
list = [102, 232, 424]
count = 0
d = {} #Empty dictionary to add values into
for i in list:
#dictionary key = count
#key.append(i)
count+=1
因此,在 for 循环中,我本质上想让 count 变量成为键,并将列表中相应的项目作为值。然后我会加一来计数,然后继续。如果我的代码在 for 循环中有点不清楚,我也很抱歉。这不是实际的代码,而只是我正在寻找的内容的一般概念。谁能帮我?谢谢。
最佳答案
您可以通过执行 dictionary[key] = item
在字典中设置项目,因此在您的情况下,您会这样做:
list = [102, 232, 424]
count = 0
d = {} #Empty dictionary to add values into
for i in list:
d[count] = i
count+=1
关于Python-尝试通过for循环创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43505921/