사전에서 일부 필드를 제거해야했지만이 필드의 키는 목록에 있습니다. 그래서이 함수를 작성합니다 :중첩 된 사전에서 필드를 제거하는 우아한 방법
def delete_keys_from_dict(dict_del, lst_keys):
"""
Delete the keys present in the lst_keys from the dictionary.
Loops recursively over nested dictionaries.
"""
dict_foo = dict_del.copy()#Used as iterator to avoid the 'DictionaryHasChanged' error
for field in dict_foo.keys():
if field in lst_keys:
del dict_del[field]
if type(dict_foo[field]) == dict:
delete_keys_from_dict(dict_del[field], lst_keys)
return dict_del
이 코드는 작동하지만 매우 우아하지는 않으며 더 나은 솔루션을 코딩 할 수 있다고 확신합니다. 이미 DICT의 모든 요소를 통해 루프를 필요로하기 때문에, 나는
흠 나는 그것이 우아한 발견을! –
나는 그것이 나쁜 코드가 아니라고 생각한다; 중첩 된 사전에 대해 재귀하는 중요한 비트가 있습니다. 아마도 isinstance (spam, collections.MutableMapping)을 더 다형 적으로 검사해야합니다. – katrielalex