Assume you’ve got the following dictionary:
JavaScript
x
3
1
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': {
2
'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}, 'key3': {'thresholds': {"orange": 3.0, "red": 5.0}, 'plotSettings': {'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}}
3
All good with that
JavaScript
1
2
1
thresholds = {key:configuration[key]['thresholds'] for key in configuration}
2
But if some of the keys don’t hold a threshold section I got the keyError.
JavaScript
1
5
1
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': {
2
'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}, 'key3': {'thresholds': {"orange": 3.0, "red": 5.0}, 'plotSettings': {'yaxisscale': 'linear', "ylabel": "bar", 'ymin': 0}}}
3
4
thresholds = {key:configuration[key]['thresholds'] for key in configuration}
5
The keyError as often described comes.
I tried to solve it this way:
JavaScript
1
3
1
thresholds = configuration.get(key, {}).get(
2
'thresholds' for key in configuration)
3
But key is not known then. How would you solve it.
Advertisement
Answer
One option is to add a check if 'thresholds'
exists
JavaScript
1
3
1
thresholds = {key: configuration[key]['thresholds'] for key in configuration if 'thresholds' in configuration[key]}
2
# {'key2': {'orange': 3.0, 'red': 5.0}, 'key3': {'orange': 3.0, 'red': 5.0}}
3
Using get()
you can do something like
JavaScript
1
3
1
thresholds = {key: configuration[key].get('thresholds', {}) for key in configuration}
2
# {'key1': {}, 'key2': {'orange': 3.0, 'red': 5.0}, 'key3': {'orange': 3.0, 'red': 5.0}}
3
however this will leave an empty dictionary in thresholds
.