python字典中的键可以是列表,使用Python提取列表中的字典键

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.

For example:

"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.

解决方案

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

Both will result in:

#throwagrenade

Rebecca Black

Eric Abidal

#questionsihate

#juniordoctors

Smiley Culture

Lily Allen

Wes Brown

Pandev

Ray Wilkins

Relevant reading:

Python docs on json (although you should only really need json.loads())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值