Elegant way to remove fields from nested dictionaries

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

    def delete_keys_from_dict(d, to_delete):
        if isinstance(to_delete, str):
            to_delete = [to_delete]
        if isinstance(d, dict):
            for single_to_delete in set(to_delete):
                if single_to_delete in d:
                    del d[single_to_delete]
            for k, v in d.items():
                delete_keys_from_dict(v, to_delete)
        elif isinstance(d, list):
            for i in d:
                delete_keys_from_dict(i, to_delete)
        return d
    
    d = {'a': 10, 'b': [{'c': 10, 'd': 10, 'a': 10}, {'a': 10}], 'c': 1 }
    delete_keys_from_dict(d, ['a', 'c']) 
    
    >>> {'b': [{'d': 10}, {}]}
    

    This solution works for dict and list in a given nested dict. The input to_delete can be a list of str to be deleted or a single str.

    Plese note, that if you remove the only key in a dict, you will get an empty dict.

提交回复
热议问题