error:TypeError: list indices must be integers or slices, not dict
this is my code
for x in canidates:
if(canidates[x]['Department']==('che'or'CHE')):
che.append(canidates[x]['reg number'])
elif(canidates[x]['Department']=='cl'or'CI'):
ci.append(canidates[x]['reg number'])
CodePudding user response:
The for loop iterates over the elements in canidates, use this:
for x in canidates:
if(x['Department']==('che'or'CHE')):
che.append(x['reg number'])
elif(x['Department']=='cl'or'CI'):
ci.append(x['reg number'])
Also better to rename it:
for canidate in canidates:
if(canidate ['Department']==('che'or'CHE')):
che.append(canidate['reg number'])
elif(canidate['Department']=='cl'or'CI'):
ci.append(canidate['reg number'])
If you need the index, you can do this:
for index, canidate in enumerate(canidates):
if(canidate ['Department']==('che'or'CHE')):
che.append(canidate['reg number'])
elif(canidate['Department']=='cl'or'CI'):
ci.append(canidate['reg number'])
CodePudding user response:
Please alter your code as follows
for x in range(len(canidates)) :
if(canidates[x]['Department']==('che'or'CHE')) :
che.append(canidates[x]['reg number'])
elif(canidates[x]['Department']=='cl'or'CI') :
ci.append(canidates[x]['reg number'])
You are trying to iterate over canidates
, a list object, in your code and access each list item in the for-loop statement. Therefore, x
is a list item, not a list index in the following statements in the body of the for-loop. Each list index must be an int
or slice
object.
To access x
as list index, you need to know the length of canidates
first. Same can be done using len(canidates)
. Then you can access each item in the canidates
list object by their indices as follows :
for x in range(len(canidates)) :
Please mind the indentation levels in Python.