Issue
I have a dictionary below that I'm trying to print the date for a certain day from. However, I'm getting a KeyError
:
{
'length': 601,
'maxPageLimit': 2500,
'totalRecords': 601,
'data': [{'date': '2021-12-13', 'newCases': 97},
{'date': '2021-12-12', 'newCases': 64},
{'date': '2021-12-10', 'newCases': 108},
{'date': '2021-12-09', 'newCases': 129}]
}
I am hoping to be able to print just 2021-12-13 and 97 for example
Solution
There is no date
key in your top-level dictionary. You need to index into data
and then choose one of the dictionaries from that value before getting a date
:
>>> dx = {
... 'length': 601,
... 'maxPageLimit': 2500,
... 'totalRecords': 601,
... 'data': [{'date': '2021-12-13', 'newCases': 97},
... {'date': '2021-12-12', 'newCases': 64}],
... }
>>> dx.get('data')
[{'date': '2021-12-13', 'newCases': 97}, {'date': '2021-12-12', 'newCases': 64}]
>>> dx.get('data')[0]
{'date': '2021-12-13', 'newCases': 97}
>>> dx.get('data')[0].get('date')
'2021-12-13'
Also, note that multiple values do not share the same key. You have multiple dictionaries in a list, each of which have matching keys - but they are not the same dictionary!
Answered By - Nathaniel Ford
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.