'IndexError: list index out of range, problems when doing a Dictionary
I have the following problem: I want to split a string and then generate a list, and then generate a dictionary. But I still get the Error IndexError. Could it be possible that I need to check if certain values do not exist?.
result=spawner.catchMumps(iterable=statement,cwd=None)
List1=result.split('^')
for x in List1:
List2=x.split(',')
#print List2[2]
Dic[List2[0]]={
'class':List2[1],
'firstname':List2[2],
'lastname':List2[3],
'mf':List2[4],
}
result
,^e:eind:77942,class:,firstname:,lastname:,mf:,^e:eind:77942,class:,firstname:,lastname:,mf:,^e:eind:77943,class:eind-jg13,firstname:Noah,lastname:Smits,mf:M,^e:eind:77943,class:eind-jg13,firstname:Noah,lastname:Smits,mf:M,^e:eind:77944,class:eind-comf-jaar,firstname:Hemshikha,lastname:Saini,mf:F,^e:eind:77944,class:eind-comf-jaar,firstname:Hemshikha,lastname:Saini,mf:F,^e:eind:77945,class:eind-budg,firstname:Cheryl,lastname:Vriese,mf:F,^e:eind:77945,class:eind-budg,firstname:Cheryl,lastname:Vriese,mf:F,^e:eind:77946,class:,firstname:,lastname:,mf:,^e:eind:77946,class:,firstname:,lastname:,mf:,^e:eind:77947,class:,firstname:,lastname:,mf:,^e:eind:77947,class:,firstname:,lastname:,mf:,^e:eind:77948,class:,firstname:,lastname:,mf:,^e:eind:77948,class:,firstname:,lastname:,mf:,^e:eind:77949,class:,firstname:,lastname:,mf:,^e:eind:77949,class:,firstname:,lastname:,mf:,^e:eind:77950,class:,firstname:,lastname:,mf:,^e:eind:77950,class:,firstname:,lastname:,mf:,^e:eind:77951,class:eind-adm,firstname:Yyy,lastname:Xxxxx,mf:,^e:eind:77951,class:eind-adm,firstname:Yyy,lastname:Xxxxx,mf:,^
The Error is:
Traceback (most recent call last):
File "lucho_new_version.py", line 28, in <module>
'class':List2[1],
IndexError: list index out of range
Solution 1:[1]
Try something like this:
List1=b.split('^')
dict_list=[]
for x in List1:
List2=x.split(',')
if len(List2) == 6: # <- This eliminates the entries which don't have the data
v = {'class':List2[1],
'firstname':List2[2],
'lastname':List2[3],
'mf':List2[4]}
dict_list.append(v)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Devang Sanghani |
