我需要将单个输入字符串转换为字典

时间:2018-05-25 06:54:43

标签: string python-3.x list dictionary

我需要将单个输入字符串转换为字典,其地方索引为键,字母为python中的值。但我被困在这里。任何帮助将不胜感激。

r = list("abcdef")    
print (r)    
for index,char in enumerate(r,0):    
indd = str(index)    
print(indd)    
abc = indd.split(",")    
list2 = list(abc)   
d = dict(zip(list2,r))    
print(d) 

2 个答案:

答案 0 :(得分:0)

这是一种使用range的方法。

<强>演示:

r = list("abcdef")
d = {}
for i in range(len(r)):
    d[i] = r[i]
print(d)

<强>输出:

{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}

使用dict()的简单方法。

r = list("abcdef")
d = dict(zip(range(len(r)), r))
print(d)

答案 1 :(得分:0)

你有一个字符串abcdef

首先列出元组的第一个元素作为位置索引,元组的第二个元素作为该索引处的字母。这可以通过这种方式完成:

tuples = list(enumerate("abcdef"))

现在,使用字典构造函数,将此元组列表转换为字典,如下所示:

dict(tuples)

<强>演示:

>>> dict(list(enumerate("abcdef")))
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}