Elegant way to remove fields from nested dictionaries

后端 未结 9 1839
傲寒
傲寒 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:22

    Since you already need to loop through every element in the dict, I'd stick with a single loop and just make sure to use a set for looking up the keys to delete

    def delete_keys_from_dict(dict_del, the_keys):
        """
        Delete the keys present in the lst_keys from the dictionary.
        Loops recursively over nested dictionaries.
        """
        # make sure the_keys is a set to get O(1) lookups
        if type(the_keys) is not set:
            the_keys = set(the_keys)
        for k,v in dict_del.items():
            if k in the_keys:
                del dict_del[k]
            if isinstance(v, dict):
                delete_keys_from_dict(v, the_keys)
        return dict_del
    

提交回复
热议问题