【问题标题】:Using Python to extract dictionary keys within a list使用 Python 提取列表中的字典键
【发布时间】:2011-07-16 04:20:18
【问题描述】:

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

列表包含多个字典,我对列表结构有点困惑。我正在尝试获取与“名称”键关联的值。

例如:

“名称”:“#throwagrenade” “名称”:“丽贝卡·布莱克” “名称”:“#questionsihate”

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

【问题讨论】:

  • 请注意,twitter 现在使用需要身份验证的 API v1.1。您可以阅读有关访问趋势的更多信息here

标签: python json list dictionary twitter


【解决方案1】:

在处理大量 json 时,我要做的第一件事就是尝试将其转换为更易读的格式。 This online json formatting tool 应该可以胜任。

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

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

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

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

for name in names:
    print name

两者都会导致:

#投掷手榴弹 丽贝卡·布莱克 埃里克·阿比达尔 #questionsihate #初级医生 笑脸文化 莉莉艾伦 韦斯布朗 潘德夫 雷·威尔金斯

相关阅读:

Python docs on json(虽然你应该只需要json.loads()

Dive Into Pythonlistsdictionaries 上的部分。

【讨论】:

【解决方案2】:

首先,该链接为您提供 JSON,因此您需要使用 json 库对其进行反序列化:

data = json.loads(response_data)

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

您可以通过简单的列表理解一次完成所有操作:

names = [item['name'] for item in data]

【讨论】:

  • 包含名字的字典列表不在数据的根目录,它们在[0]['trends']
【解决方案3】:
import urllib2
import json

url = 'http://api.twitter.com/1/trends/44418.json'
data = urllib2.urlopen(url).read()
j = json.loads(data)

names = [d['name'] for d in j[0]['trends']]

结果

names = [u'#throwagrenade', u'Rebecca Black', u'#questionsihate',
    u'#thingsthatdontgotogether', u'Eric Abidal', u'Smiley Culture',
    u'Ray Wilkins', u'Wes Brown', u'Twenty Twelve', u'Marseille']

【讨论】:

    【解决方案4】:

    这是一个 JSON 文件,因此您需要使用 JSON 解析器来读取它。 Python 2.7 中有 a parser - 只是 import json。使用该结构,您可以从 Python 操作它。

    如果您真的不关心 name 键在结构中的哪个位置,您可以通过树递归查找它们 (if key == "name"),或者使用正则表达式。

    不过,正则表达式会很麻烦,因为需要在匹配中包含转义字符。

    【讨论】:

    • 使用正则表达式的想法让我想想就头疼!
    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2023-03-27
    相关资源
    最近更新 更多