我不得不從字典中刪除一些字段,這些字段的鍵位於列表中。所以,我寫這篇文章的功能:從嵌套字典中刪除字段的優雅方法
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
此代碼的工作,但它不是很優雅,我敢肯定,你可以編寫一個更好的解決方案。
嗯我覺得很優雅! – 2010-08-04 13:04:22
我認爲這不是錯誤的代碼;你已經獲得了嵌套字典遞歸的重要位。你應該檢查'isinstance(spam,collections.MutableMapping)'是否更多態。 – katrielalex 2010-08-04 13:04:30