Home > other >  Accessing an element in a slightly complicated dictionary
Accessing an element in a slightly complicated dictionary

Time:12-24

import requests
api="https://api.rootnet.in/covid19-in/stats/latest"
response=requests.get(api)
local_case_tracker=response.json()
print(local_case_tracker.items())
print(local_case_tracker['data'])
print(local_case_tracker['data']['regional'])

So I'm trying to build a Covid tracker(global and local, and by local i mean my own country) using python.If you run the code you get to see a really big and branched dictionary and I wish to access any one of the states in that dictionary (lets say Goa) but i cant do so, so I tried to break down the problem by doing this

print(local_case_tracker['data'])
print(local_case_tracker['data']['regional'])

Im able to fetch some results but when i try

print(local_case_tracker['data']['regional']['loc : Goa'])

i get a: TypeError: list indices must be integers or slices, not str

Its a very stupid doubt but ive been scratching my head over this since the last 30 min.

CodePudding user response:

local_case_tracker['data']['regional']is a Python List (of Dictionaries) so should be accessed by index, stepping through by or searching through. Try this to get the data for Goa.

for item in local_case_tracker['data']['regional']:
    if item['loc'] == 'Goa':
        print(item)

You could just save the item instead of printing it; it is a Dictionary so could access the values using the various keys. Also try this to see all the locations

for item in local_case_tracker['data']['regional']:
    print(item['loc'])
  • Related