2

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

akozi
  • 425
  • 1
  • 7
  • 20
GursimranSe
  • 99
  • 2
  • 8

2 Answers2

9

Let's use comprehension and split:

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

Output:

{'a': '65', 'b': '66', 'c': '67'}
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
0

You are using index i to iterate over L, but you use (i+1) to access A, this will lead to the problem. A might not have the size of Len(L)

Vasco Lopes
  • 141
  • 9