2017-04-19 4783 views
1

我想通过使用for循环创建字典。我有一个有序的列表,我试图将列表中的值与有序的数字进行匹配。例如: {0:100, 1:423, 2:434}Python - 尝试通过for循环创建字典

我只是有麻烦的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循环基本上我想使计数变量的关键,而在列表作为值的相应项目。然后我会加一个数来计算,然后继续。另外我很抱歉,如果我的代码在for循环中有点不清楚。这不是实际的代码,而只是我所寻找的一般概念。谁能帮我?谢谢。

回答

4

你做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 
+1

可替代地,对于'IDX,项目在枚举列表:d [索引] = item' – FCo

+3

另外可替换地,字符'D = {K:v对于K,V在枚举(列表)}' – Alden

0

您可以在同一行做到不使用For循环或计数器变量:

dict(zip(range(0, len(list)), list)) 
0

您可以使用枚举:

list = [102, 232, 424] 
d = {} 

for a, b in enumerate(list): 
    d[a] = b 

,或者使用字典comprehe nsion:

d = {a:b for a, b in enumerate(list)}