问题描述
输入以下网址时,我收到了一个列表 -
I received a list when inputting the following URL - http://api.twitter.com/1/trends/44418.json
该列表包含多个字典,我对列表结构有点混淆。我正在尝试获取与名称密钥相关联的值。
The list contains multiple dictionaries, and I'm a bit confused with the list structure. I'm trying to obtain the values associated with the 'name' key.
例如:
名称:#throwagrenade
name:Rebecca Black
name:#questionsihate
"name":"#throwagrenade" "name":"Rebecca Black" "name":"#questionsihate"
自己编写代码,我只是想从概念上了解如何在列表中访问字典(及其键/值对)。
I can write the code myself, I'm just trying to conceptually understand how to access dictionaries (and their key/value pairs) within a list.
推荐答案
在使用大块json时,我会做的第一件事是尝试将其变成更可读的格式。 应该做这个工作。
The first thing I would do when working with a big lump of json, is try to get it into a more readable format. This online json formatting tool should do the job.
这里有一些代码可以获取所有的趋势名称:
Here's some code that will get all the trend names:
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']
或者您可以在一行中完成所有操作:
Or you can do it all in one line:
names = [trend['name'] for trend in the_data[0]['trends']]
for name in names:
print name
都会导致:
#throwagrenade
Rebecca Black
Eric Abidal
#questionsihate
#juniordoctors
Smiley Culture
Lily Allen
Wes Brown
Pandev
Ray Wilkins
相关阅读:
(虽然你只需要真正需要 json.loads()
)
Python docs on json (although you should only really need json.loads()
)
和。
这篇关于使用Python提取列表中的字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!