如何使用python访问json文件字典中的键值

如何使用python访问json文件字典中的键值

本文介绍了如何使用python访问json文件字典中的键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,可以从api中提取json数据,并希望在提取数据后对其进行解码,然后选择要存储到db中的标签.现在,我只需要获取脚本以返回特定的被调用值即可.这就是脚本的外观,在我尝试对其进行解码之前.

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 script to return specific called upon values. this is what the script looks like, before me trying to decode it.

import requests
def call():
payload = {'apikey':'945e8e8499474b7e8d2bc17d87191bce', 'zip' : '47120'}
bas_url = 'http://congress.api.sunlightfoundation.com/legislators/locate'
r = requests.get(bas_url, params = payload)
grab = r.json()
return grab

那是返回的json数据,我想专门调用IE {'twitter_id': 'RepToddYoung'}, or {'first_name': 'Todd'}

thats the json data returned, i want to specifically call upon IE {'twitter_id': 'RepToddYoung'}, or {'first_name': 'Todd'}

代替我的脚本返回它检索的整个json文件

Instead of my script returning the entire json file that it retrieves

推荐答案

查看返回的数据结构.这是一本包含字典列表的字典.您可以使用'results'键访问列表:

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'])

您可以简化为:

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

可能您将要遍历列表:

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

它将输出:


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

这篇关于如何使用python访问json文件字典中的键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 05:05