Skip to content Skip to sidebar Skip to footer

How To Access Key Values In A Json Files Dictionaries With Python

I have a script that pulls json data from an api, and I want it to then after pulling said data, decode and pick which tags to store into a db. Right now I just need to get the scr

Solution 1:

Look at the data structure that you are getting back. It's a dictionary that contains a list of dictionaries. You can access the list using the 'results' key:

l = r.json()['results']

From there the dictionary containing the item you are after is the first item of the list, so:

d = l[0]

And the specific values can be retrieved from the dictionary:

print(d['twitter_id'])
print(d['first_name'])

You can simplify that to this:

r.json()['results'][0]['twitter_id']
r.json()['results'][0]['first_name']

Probably you will want to iterate over the list:

for d in r.json()['results']:
    print('{first_name} {last_name}: {twitter_id}'.format(**d))

which will output:

Todd Young: RepToddYoung
Joe Donnelly: SenDonnelly
Daniel Coats: SenDanCoats

Post a Comment for "How To Access Key Values In A Json Files Dictionaries With Python"