python - recursively deleting dict keys?

前端 未结 3 1494

I\'m using Python 2.7 with plistlib to import a .plist in a nested dict/array form, then look for a particular key and delete it wherever I see it.

When it

3条回答
  •  故里飘歌
    2021-02-06 11:34

    Here a generalized version of the one of @bruno desthuilliers, with a callable to test against the keys.

    def clean_dict(obj, func):
        """
        This method scrolls the entire 'obj' to delete every key for which the 'callable' returns
        True
    
        :param obj: a dictionary or a list of dictionaries to clean
        :param func: a callable that takes a key in argument and return True for each key to delete
        """
        if isinstance(obj, dict):
            # the call to `list` is useless for py2 but makes
            # the code py2/py3 compatible
            for key in list(obj.keys()):
                if func(key):
                    del obj[key]
                else:
                    clean_dict(obj[key], func)
        elif isinstance(obj, list):
            for i in reversed(range(len(obj))):
                if func(obj[i]):
                    del obj[i]
                else:
                    clean_dict(obj[i], func)
    
        else:
            # neither a dict nor a list, do nothing
            pass
    

    And an example with a regex callable :

    func = lambda key: re.match(r"^
    ", key) clean_dict(obj, func)

提交回复
热议问题