首页 > 解决方案 > 提取字典中的特定键值

问题描述

我正在学习使用 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

所以任何关于我需要什么的帮助或解释都会很棒。谢谢!

标签: pythonjson

解决方案


正如错误所暗示的那样,列表索引必须是“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

推荐阅读