Reputation: 129
I am trying to use defaultdict(dict) to parse data from json that has nested keys of 'date' and 'value'.
The date key is always presented with the corresponding value but if there is no data on the 'value' -key at all, it is completely omitted.
This is causing me a problem with defaultdict because when on the first row the 'value' key is missing but is present on the second row it raises an KeyError: 'value'.
Any ideas how i could work around this and have the value in there even thought its missing on the first row.
DATA:
{
"metric": "complexity",
"history": [
{
"date": "2019-09-10T15:24:33+0200",
"value": "54"
},
{
"date": "2019-12-24T11:26:42+0100"
}
CODE:
dates_to_values = defaultdict(dict)
for metric in metrics['measures']:
metric_value = metric['metric']
for hist in metric['history']:
dates_to_values[hist['date']][metric_value] = hist['value']
Upvotes: 2
Views: 4371
Reputation: 1620
The problem is not in defaultdict
but in hist
. If hist
is always be a dict then use hist.get('value')
when key is not always present in it.
Upvotes: 3