我不得不从字典中删除一些字段,这些字段的键位于列表中。所以,我写这篇文章的功能:从嵌套字典中删除字段的优雅方法
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