파이썬(Python) 에러 KeyError 와 처리 방법
2월 14, 2023
In Python |
## 파이썬(Python) 에러 KeyError ### 원인 Python의 KeyError는 딕셔너리에 존재하지 않는 키를 사용하여 딕셔너리에 접근할 때 발생합니다. 아래는 KeyError가 발생할 수 있는 코드의 예입니다. File: test.py ```python dic = {'test1': 1, 'test2': 2} print(dic['test3']) ``` 결과 ```python $ python test.py File "/test.py", line 2, in print(dic['test3']) KeyError: 'test3' ``` 딕셔너리에 해당하는 키가 없기 때문에 발생합니다. ### 처리 방법 이런 종류의 에러를 방지하려면 딕셔너리에 직접 접근하는 대신 키를 찾을 수 없으면 None을 리턴하는 get() 메서드를 사용하면 좋습니다. File: test.py ```python dic = {'test1': 1, 'test2': 2} test_value = dic.get('test3') if test_value is not None: print(test_value) else: print("test value not found") ```