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
CodePudding user response:
As it's currently setup, you have your top-most dictionary with keys: length, maxPage, TotalyRecords and data. And then inside of data, you have a list with 2 indexes, each index being it's own dictionary.
If you wanted to get the dictionary for dec 13th, it'd be:
dict['data'][0] # First we go to the "data" key and get that. Then inside of the
data key we get index 0, which is {'date': '2021-12-13', 'newCases': 97}
If you wanted specifically the number of newcases, for example, it'd be:
dict['data'][0]['newCases'])
It's just about working your way down the chain of nested dictionaries and lists you have. Though there's probably a better way to accomplish what you're trying to do tbh
CodePudding user response:
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!
CodePudding user response:
dates are used as values in your program so you need to use some kind of loop to access the required date.
for date in d['data']:
if date['date'] == foo:
# do your processing