Nick Wright Nick Wright - 9 days ago 5
Python Question

TypeError: 'int' object is not subscriptable Can't figure this out

I tried writing some code but when I ran it, it returned the error "TypeError: 'int' object is not subscriptable":

This is the line of code:

if data[key][0] == b[0] and data[key][1] == b[1]:


'data' is a dictionary with 'key' being the key and '0' being the value (before the 'and')

I just need to know why this is happening and how it can be fixed. Thanks :)

Example of code

data = {
'a' : ['1','1'],
'b' : ['1','2'],
'c' : ['1','3'],
'd' : ['1','4'],
'e' : ['1','5'],
'f' : ['2','1'],
'g' : ['2','2'],
'h' : ['2','3'],
'i' : ['2','4'],
'j' : ['2','4'],
'k' : ['2','5'],
'l' : ['3','1'],
'm' : ['3','2'],
'n' : ['3','3'],
'o' : ['3','4'],
'p' : ['3','5'],
'q' : ['4','1'],
'r' : ['4','2'],
's' : ['4','3'],
't' : ['4','4'],
'u' : ['4','5'],
'v' : ['5','1'],
'w' : ['5','2'],
'x' : ['5','3'],
'y' : ['5','4'],
'z' : ['5','5']
}


total = '21333534313511424214'
count = 0
b = []
finalOuput = []
for number in total:
if count == 2:
for number in b:
for key in data:
if data[key][0] == b[0] and data[key][1] == b[1]:
finalOutput.append(b[0])
finalOutput.append(b[1])
count = 0
b = 0
total.replace(number,'')
else:
continue
else:
b.append(number)
count += 1
continue

Answer

You have redefined b from a list to int hence it cant be indexed.

Relevant excerpt from your code:

if data[key][0] == b[0] and data[key][1] == b[1]:
    finalOuput.append(b[0])
    finalOutput.append(b[1])
    count = 0

    ## b has been redefined as 0 hence `b[0]` causes error ##
    b = 0     

    total.replace(number,'')
else:
    continue