Elegant way to remove fields from nested dictionaries

后端 未结 9 1838
傲寒
傲寒 2020-12-05 03:04

I had to remove some fields from a dictionary, the keys for those fields are on a list. So I wrote this function:

def delete_keys_from_dict(dict_del, lst_key         


        
9条回答
  •  鱼传尺愫
    2020-12-05 03:27

    Using the awesome code from this post and add a small statement:

        def remove_fields(self, d, list_of_keys_to_remove):
            if not isinstance(d, (dict, list)):
                return d
            if isinstance(d, list):
                return [v for v in (self.remove_fields(v, list_of_keys_to_remove) for v in d) if v]
            return {k: v for k, v in ((k, self.remove_fields(v, list_of_keys_to_remove)) for k, v in d.items()) if k not in list_of_keys_to_remove}
    

提交回复
热议问题