Delete dict and subdict items of some name

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Dec 18 01:22:14 CET 2012


On 17 December 2012 23:44, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
> On 17 December 2012 23:08, MRAB <python at mrabarnett.plus.com> wrote:
>> Wouldn't a set of the id of the visited objects work?
>
> Of course it would. This is just a tree search.
>
> Here's a depth-first-search function:
>
> def dfs(root, childfunc, func):
>     '''depth first search on a tree
>     calls func(node) once for each node'''
>     visited = set()
>     visiting = OrderedDict()
>     visiting[id(root)] = it = iter([root])
>
>     while True:
>         try:
>             node = next(it)
>         except StopIteration:
>             try:
>                 node, it = visiting.popitem()
>             except KeyError:
>                 return
>         key = id(node)
>         if isinstance(node, dict) and key not in visited:
>             func(node)
>             visiting[key] = it = iter(childfunc(node))
>             visited.add(key)
>
> Now you can do:
>
> dfs(my_dict_tree, lambda x: x.pop('Favicon', None))

Slight correction:
dfs(g, lambda n: n.values(), lambda x: x.pop('Favicon', None))


Oscar



More information about the Python-list mailing list