에러노트

(Python) 'int' object is not subscriptable

린예라 2024. 3. 2. 17:49

def write(data, value):
    indexkey = get_key(data)
    hash_address = hash_function(indexkey)
    if hash_table[hash_address] != 0:
        for idx in range(len(hash_table[hash_address])):
            if hash_table[hash_address][idx][0]==indexkey:
                hash_table[hash_address][idx][1] = value
                return
            
        hash_table[hash_address].append([indexkey, value])
    
    else:
        hash_table[hash_address]=([indexkey, value])

 

다음과 같이 해쉬테이블 관련 로직을 짜는데 

'int' object is not subscriptable

라고 하는 오류가 자꾸 나서 문제를 도저히 찾을 수 없다가 겨우 발견함.

위의 오류는 인덱스가 없는 자료형태에 접근하면 생기는 경우가 많음.

마지막줄

hash_table[hash_address]=([indexkey, value])

이거를 괄호를 잘못쳐서 생긴 오류였음

괄호를 저렇게 치면 저 키랑 밸류값이 리스트형태로 묶어져서 하나로 들어가는게 아니라

각각 리스트에 하나씩 따로 들어가게 되어서 생긴 오류였음

 

indexkey와 value를 하나로 묶어서 리스트 형태로 집어 넣으려면

다음과 같이 수정해야함

 

hash_table[hash_address]=[[indexkey, value]]