eljobso eljobso - 2 months ago 4x
Python Question

Check whether a nested dict is False in the leaf nodes in python

Let's say I have a nested dict, e.g. the following

{'agent1': {'status': True},
'block1': {'status': True, 'number': False, 'usable_by': True, 'location': True, 'skill':
{'speed': False, 'flexibility': True}}}

At the lowest key level (the leaves) of this dict, the values are only boolean (True or False). The input dict can basically have any kind of nested structure with different names as keys and no fixed depth.

How can I check in general, whether there is
in a given dict.


You'd have to traverse the dictionaries, and you want to exit early:

def any_false_leaf(d):
    if isinstance(d, dict):
        return any(any_false_leaf(v) for v in d.values())
    return not d

This recurses through your dictionaries, and returns True if there is a nested false value in the structure. Using the any() function and a generator expression guarantees that the result is produced as soon as such a value is found.


>>> d = {'agent1': {'status': True},
...  'block1': {'status': True, 'number': False, 'usable_by': True, 'location': True, 'skill':
...                 {'speed': False, 'flexibility': True}}}
>>> any_false_leaf(d)
>>> any_false_leaf({'foo': True})
>>> any_false_leaf({'foo': {'bar': True}})
>>> any_false_leaf({'foo': {'bar': True, 'spam': False}})