如何在python 3中将字符串转换为字典

Gur*_*der 1 python dictionary python-3.x

从字符串开始:

S='a=65 b=66 c=67'
Run Code Online (Sandbox Code Playgroud)

你会如何创建一个类似于dict的输出 {'a':'65','b':'66','c':'67'}

尝试:

S='a=65 b=66 c=67'
L=s.split(' ')
D=dict()
A=''
i=0
While i<Len(L):
    A=L[i].split('=')
    D[a[i]]=a[i+1]
    i+2

print (D)
Run Code Online (Sandbox Code Playgroud)

第8行indexerror列表索引超出范围时出错

Sco*_*ton 8

让我们使用理解和分裂:

dict(i.split('=') for i in S.split())
Run Code Online (Sandbox Code Playgroud)

输出:

{'a': '65', 'b': '66', 'c': '67'}
Run Code Online (Sandbox Code Playgroud)