IT/Programming

[Python] dictionary changed size during iteration 해결

이녀기 2023. 6. 24. 00:14

문제 상황

keys = target_dict.keys()
for key in keys:
	if condition(key):
    	target_dict.pop(key)
Runtime Error: dictionary changed size during iteration

딕셔너리에서 key를 체크하면서 조건에 맞는 key-value pair를 제거하려 했는데, 에러가 났다.

 

해결

target_dict.keys() 대신 list(target_dict.keys()) 를 이용한다.

.keys() method는 list가 아니라 dict와 연결된 iterable object를 반환하는 것 같다.

keys = list(target_dict.keys())
for key in keys:
	if condition(key):
    	target_dict.pop(key)

list() 함수를 이용해 딕셔너리를 참조하지 않는 리스트로 만들면 에러 없이 실행할 수 있다.