python - Elegant way to remove fields from nested dictionaries -


I had to remove some fields from a dictionary, the keys in this area are on a list, then I type this function:

  def delete_keys_from_dict (dict_del, lst_keys): "" "Delete the key in lst_keys from the dictionary, repeatedly loop on nested dictionaries." "Dict_foo = dict_del .copy () is used as an iterator to avoid 'dictionary: side-changel' error for fields in dict_foo.keys (): If the field contains lst_keys: del dict_del [field] if type ( Dict_foo [field]) == dict: delete_keys_from_dict (dict_del [field], lst_keys) return dict_del  

This code works, but it is not very elegant and I'm sure you Better solution codes can be done in advance.

  def delete_keys_from_dict (dict_del, lst_keys) For: l Lst_keys: try: del dict_del [k] except for keyError: pass for v in dict_del.values ​​(): If ifinstance (v, dict): delete_keys_from_dict (v, lst_keys) return dict_del  

Comments

Popular posts from this blog

Eclipse CDT variable colors in editor -

AJAX doesn't send POST query -

wpf - Custom Message Box Advice -