使用键将列表附加到字典

时间:2019-09-28 19:35:32

标签: python dictionary

我正在尝试创建一个包含枚举列表中的键的字典,该字典会将枚举值作为键分配给列表的值。

import string

dic = string.ascii_lowercase
s_dic = []
n_dic = {}    ## New Dictionary to contain numbers:letters

for i in dic:
    s_dic.append(i)  
for number, letter in enumerate(s_dic, start=1):
    print(number, '=', letter)

我使用print只是为了测试工作代码。输出符合预期:

1 = a
2 = b
3 = c
4 = d
5 = e
6 = f
7 = g
8 = h
9 = i
10 = j
11 = k
12 = l
13 = m
14 = n
15 = o
16 = p
17 = q
18 = r
19 = s
20 = t
21 = u
22 = v
23 = w
24 = x
25 = y
26 = z

我希望n_dic包含{1:a, 2:b etc}

3 个答案:

答案 0 :(得分:3)

Iiuc,你可以尝试

n_dic = {i: v for i, v in enumerate(s_dic, start=1)}

这是初始化字典的标准方法,称为字典理解

答案 1 :(得分:2)

您可以直接从枚举创建字典

n_dic = dict(enumerate(s_dic, start=1))

>>> s_dic = list('abcdefg')
>>> dict(enumerate(s_dic, start=1))
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g'}

甚至(感谢@SayandipDutta)

dic = string.ascii_lowercase
dict(enumerate(dic, start=1))

答案 2 :(得分:0)

这可能是您想要的

import string
dic = string.ascii_lowercase 
s_dic = [] 
n_dic = {} ## New Dictionary to contain numbers:letters 
for i in dic: 
     s_dic.append(i)

id = 0
for letter in s_dic:
     id = id + 1
     n_dic[id] = letter