린스토리

[Python-Dictionary] RuntimeError: dictionary changed size during iteration 에러 해결과 Pop & Del 차이 본문

Python/Python

[Python-Dictionary] RuntimeError: dictionary changed size during iteration 에러 해결과 Pop & Del 차이

rinaaaLee 2022. 7. 26. 17:01

Key 와 Value로 이루어진 Dictionary에서 특정 value를 가진 key를 삭제하고 싶을 때, 

RuntimeError: dictionary changed size during iteration

이런 에러를 만났다. 

해결하는 방법에 대해 알아보자.


이렇게 dictionary를 만들었다. 
value가 4000인 key를 지우고자 다음과 같이 코드를 작성해보았다.

for key in test_dict.keys():
    if test_dict[key] == 4000:
        test_dict.pop(key)

그랬더니, 

이런 에러가 나왔다. 


Dictionary에서 값을 지우고 싶을 때는 두 가지 방법이 있는데, 

1. Pop ()

2. Del []

method를 사용하는 것이다. 

 

두 방법의 차이점은, 

1. Pop은 반환값이 있으나

2. Del은 반환값이 없다는 것이다. 


아마도... pop을 적용하면서 저런 에러가 나온 것 같다. 

해결 방법은..!

for key in test_dict.keys():
    if test_dict[key] == 4000:
        del test_dict[key]

pop을 del로 적용하니 문제없이 삭제가 되었다. 

 

'Python > Python' 카테고리의 다른 글

[Error] "TypeError: decoding str is not supported" 해결  (0) 2022.08.02
Comments