Skip to content
Advertisement

accessing nested dictionary, that holds empty entries in python with get method and for loop that

Assume you’ve got the following dictionary:

configuration = {'key1':{'thresholds': {"orange": 3.0, "red": 5.0}, {'plotSettings': {'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}, 'key2': {'thresholds': {"orange": 3.0, "red": 5.0}, 'plotSettings': {
        'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}, 'key3': {'thresholds': {"orange": 3.0, "red": 5.0}, 'plotSettings': {'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}}

All good with that

thresholds = {key:configuration[key]['thresholds'] for key in configuration}

But if some of the keys don’t hold a threshold section I got the keyError.

configuration = {'key1':{'thresholds': {"orange": 3.0, "red": 5.0}, {'plotSettings': {'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}, 'key2': {'thresholds': {"orange": 3.0, "red": 5.0}, 'plotSettings': {
        'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}, 'key3': {'thresholds': {"orange": 3.0, "red": 5.0}, 'plotSettings': {'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}}

thresholds = {key:configuration[key]['thresholds'] for key in configuration}

The keyError as often described comes.

I tried to solve it this way:

thresholds = configuration.get(key, {}).get(
        'thresholds' for key in configuration)

But key is not known then. How would you solve it.

Advertisement

Answer

One option is to add a check if 'thresholds' exists

thresholds = {key: configuration[key]['thresholds'] for key in configuration if 'thresholds' in configuration[key]}
# {'key2': {'orange': 3.0, 'red': 5.0}, 'key3': {'orange': 3.0, 'red': 5.0}}

Using get() you can do something like

thresholds = {key: configuration[key].get('thresholds', {}) for key in configuration}
# {'key1': {}, 'key2': {'orange': 3.0, 'red': 5.0}, 'key3': {'orange': 3.0, 'red': 5.0}}

however this will leave an empty dictionary in thresholds.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement