[Python] dict 에서 RuntimeError: dictionary changed size during iteration 해결하는 방법

2020. 4. 11. 15:25분석 Python/구현 및 자료

728x90

현재 하고자 하는 것은 다음과 같다. 사용하지 않는 키는 지워버리고 싶다. 
사용하지 않는 것을 확인하는 방법은 키에 해당하는 값이 None이면 제거하려고 했다.
하지만 Loop 도중에 key를 제거하려다 보니 에러가 발생했다. 
그래서 나중에도 이러한 상황을 다시 겪을 수 있으니 정리를 해놓는다.

해결 방법은 다음과 같다.

## 1 값에서 제거하고자 하는 경우
for key , type_ck in list(current_dict.items()) : ## list , items를 꼭 써야함.
    if type(type_ck) != dict :
        del current_dict[key]

## 지우고자 하는 키를 알경우
remove_key = ['Category', 'NewVar']
for key in list(current_dict.keys()) : ## list와 keys()를 꼭 써야함.
    if key in remove_key :
        del current_dict[key]

마지막 꺼는 보통 지우기 위해서 loop를 쓰는데, list와 map을 사용해서도 지울 수 있다는 것을 정리하기 위해 기록

## 3
remove_key = []
for key , type_ck in current_dict.items() :
    if type(type_ck) != dict :
        remove_key.append(key)
remove_key
### list map을 사용해서 loop 방식이 아닌 그냥 지우기
list(map(current_dict.pop, remove_key))

 

 

https://stackoverflow.com/questions/5384914/how-to-delete-items-from-a-dictionary-while-iterating-over-it

 

How to delete items from a dictionary while iterating over it?

Is it legitimate to delete items from a dictionary in Python while iterating over it? For example: for k, v in mydict.iteritems(): if k == val: del mydict[k] The idea is to remove elements

stackoverflow.com

 

728x90