python - 提取字典中的特定键值
问题描述
我正在学习使用 Python 和 Twitter API。用户信息保存为 json 文件。
基本上 json 文件存储了一个字典列表:
data = [{1}, {2}, {3}, {4}, {5}]
在每个字典中都有一些信息,例如:
[
{
"created_at": "2018-04-28 13:12:07",
"favorite_count": 0,
"followers_count": 2,
"id_str": "990217093206310912",
"in_reply_to_screen_name": null,
"retweet_count": 0,
"screen_name": "SyerahMizi",
"text": "u can count on me like 123 \ud83d\ude0a\ud83d\udc6d"
},
{
"created_at": "2018-04-26 04:21:48",
"favorite_count": 0,
"followers_count": 2,
"id_str": "989358860937846785",
"in_reply_to_screen_name": null,
"retweet_count": 0,
"screen_name": "SyerahMizi",
"text": "Never give up"
},
]
我只是想只打印每个字典中的“文本”信息,但我一直收到错误
TypeError: list indices must be integers, not str
这是我到目前为止所拥有的:
import json
with open('981452637_tweetlist.json') as json_file:
json_data = json.load(json_file)
lst = json_file['text'][0]
print lst
所以任何关于我需要什么的帮助或解释都会很棒。谢谢!
解决方案
正如错误所暗示的那样,列表索引必须是“int”而不是“str”。您错误地将列表视为字典,将字典视为列表。正确的代码将是:
import json
with open('981452637_tweetlist.json') as json_file:
json_data = json.load(json_file)
lst = json_file[0]['text'] #change here
print lst
推荐阅读
- javascript - 客户端获取请求头
- azure-container-service - 公司代理后面的私有 VNET 中的 AKS
- java - 如何放置两个不同版本的依赖项?- Maven - Java - 春天
- azure-devops - VSTS 构建寻找不存在的驱动器
- google-sheets - 将 Google 表格中最后日期的列标题作为数组公式返回
- sql - 不能 DROP FUNCTION 因为它被对象引用
- javascript - d3.timer() 帧 - 减速
- python - Pandas:根据其他列值有条件地替换值
- java - 基于对象拆分为列表,无需实例
- css - 在 Ubuntu 下找不到随机数的 CSS 文件