Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string into dictionary in python 3 [duplicate]

Beginning with a string like:

S='a=65 b=66 c=67'

How would you create an output a dict like {'a':'65','b':'66','c':'67'}

Attempt:

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)

Error on line 8 indexerror list index out of range

like image 500
GursimranSe Avatar asked Jun 21 '26 02:06

GursimranSe


1 Answers

Let's use comprehension and split:

dict(i.split('=') for i in S.split())

Output:

{'a': '65', 'b': '66', 'c': '67'}
like image 51
Scott Boston Avatar answered Jun 22 '26 15:06

Scott Boston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!