使用Python提取列表中的字典键

Ale*_*sch 11 python twitter json dictionary list

我在输入以下网址时收到了一个列表 - http://api.twitter.com/1/trends/44418.json

该列表包含多个词典,我对列表结构有点困惑.我正在尝试获取与"name"键关联的值.

例如:

"名字":"#throwagrenade""名字":"丽贝卡·布莱克""名字":"#questionsihate"

我可以自己编写代码,我只是想在概念上理解如何在列表中访问字典(及其键/值对).

Aco*_*orn 22

在处理一大块json时,我要做的第一件事是尝试将其变为更易读的格式.这个在线json格式化工具应该可以完成这项工作.

这里有一些代码可以获得所有趋势名称:

import urllib2
import json

url = 'http://api.twitter.com/1/trends/44418.json'

# download the json string
json_string = urllib2.urlopen(url).read()

# de-serialize the string so that we can work with it
the_data = json.loads(json_string)

# get the list of trends
trends = the_data[0]['trends']

# print the name of each trend
for trend in trends:
    print trend['name']
Run Code Online (Sandbox Code Playgroud)

或者您可以在一行中完成所有操作:

names = [trend['name'] for trend in the_data[0]['trends']]

for name in names:
    print name
Run Code Online (Sandbox Code Playgroud)

两者都会导致:

#throwagrenade
Rebecca Black
Eric Abidal
#questionsihate
#juniordoctors
Smiley Culture
Lily Allen
Wes Brown
Pandev
Ray Wilkins

相关阅读:

关于json的Python文档(尽管你应该只需要json.loads())

深入研究Python关于列表和词典的部分.


Dan*_*man 8

好吧,首先,该链接为您提供JSON,因此您需要使用json库反序列化它:

data = json.loads(response_data)
Run Code Online (Sandbox Code Playgroud)

现在你只需要一个词典列表.您可以使用循环轻松遍历列表for.在每次迭代中,您都有一个普通的字典,您可以name使用通常的字典语法从中获取与该键对应的值.

您可以使用简单的列表理解立即完成整个事情:

names = [item['name'] for item in data]
Run Code Online (Sandbox Code Playgroud)