Elegant way to remove fields from nested dictionaries

后端 未结 9 1782
傲寒
傲寒 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}
    
    0 讨论(0)
  • 2020-12-05 03:33

    this works with dicts containing Iterables (list, ...) that may contain dict. Python 3. For Python 2 unicode should also be excluded from the iteration. Also there may be some iterables that don't work that I'm not aware of. (i.e. will lead to inifinite recursion)

    from collections.abc import Iterable
    
    def deep_omit(d, keys):
        if isinstance(d, dict):
            for k in keys:
                d.pop(k, None)
            for v in d.values():
                deep_omit(v, keys)
        elif isinstance(d, Iterable) and not isinstance(d, str):
            for e in d:
                deep_omit(e, keys)
    
        return d
    
    0 讨论(0)
  • 2020-12-05 03:35
    def delete_keys_from_dict(dict_del, lst_keys):
        for k in lst_keys:
            try:
                del dict_del[k]
            except KeyError:
                pass
        for v in dict_del.values():
            if isinstance(v, dict):
                delete_keys_from_dict(v, lst_keys)
    
        return dict_del
    
    0 讨论(0)
提交回复
热议问题