【问题标题】:I need to convert a single input string into a dictionary我需要将单个输入字符串转换为字典
【发布时间】:2018-05-25 06:54:43
【问题描述】:

我需要将单个输入字符串转换为字典,其中位置索引作为键,字母作为 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) 

【问题讨论】:

  • 请花时间正确格式化您的代码。
  • 您在寻找d = dict(enumerate('abcdef'))吗?
  • 您真的希望键是字符串还是数字?

标签: string python-3.x list dictionary


【解决方案1】:

这是使用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)

【讨论】:

    【解决方案2】:

    你有一个字符串abcdef

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

    tuples = list(enumerate("abcdef"))
    

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

    dict(tuples)
    

    演示:

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

    【讨论】:

      猜你喜欢
      • 2023-01-28
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      • 2011-04-11
      • 2017-10-09
      • 1970-01-01
      • 2011-12-22
      • 2011-02-11
      相关资源
      最近更新 更多