하루한줄 코딩일기
[Python] TypeError: 'dict_values' object is not subscriptable 본문
Languages./Python
[Python] TypeError: 'dict_values' object is not subscriptable
jjuha 2022. 2. 2. 17:32📃 'dict_values' object is not subscriptable 에러
해당 에러가 발생한 코드의 일부다. collections.Counter의 values() 중 특정 인덱스에 접근하고자 했을 때 오류가 발생했다.
for i in range(len(id_list)):
if id_list[i] in collections.Counter(result).keys():
id_list[i] = collections.Counter(result).values()[i] #오류 발생 지점
Traceback (most recent call last):
File "C:\Users\14Z980-GA50K\Desktop\AA\AA\AA.py", line 38, in <module>
id_list[i] = collections.Counter(result).values()[i]
TypeError: 'dict_values' object is not subscriptable
👊 리스트로 변환 후 인덱스에 접근
python 3.x부터 dict.values()는 리스트 오브젝트가 아닌 dict-values 오브젝트를 반환하는데, 이는 해시 테이블 형식으로 자료를 저장하기 때문에 인덱싱에 적합하지 않다. 따라서 특정 인덱스에 접근하기 위해서는 dict.values를 리스트로 변환한 후 값에 접근해야 한다.
id_list[i] = list(collections.Counter(result).values())[i]
[참고] Python: how to convert a dictionary into a subscriptable array?
'Languages. > Python' 카테고리의 다른 글
[Python] 정규표현식 re.sub을 이용한 문자열 치환하기 (0) | 2022.02.16 |
---|---|
[Python] 순열(permutations)과 조합(combinations) 구현하기 (0) | 2022.02.14 |
[Python] input()과 sys.stdin.readline()의 차이 (0) | 2022.01.27 |
[Python] TypeError: 'int' object is not callable (0) | 2022.01.26 |
Comments