首页 > 解决方案 > Python - 获取特定键的所有值

问题描述

我目前正在使用 twitter API。到目前为止,我设法将特定的推文作为 json 和漂亮的打印出来。这是输出:

{
    "contributors": null,
    "coordinates": null,
    "created_at": "Sun Jun 28 12:32:35 +0000 2020",
    "display_text_range": [
        19,
        23
    ],
    "entities": {
        "hashtags": [],
        "symbols": [],
        "urls": [],
        "user_mentions": [
            {
                "id": 11883745733410470,
                "id_str": "11883745733410470",
                "indices": [
                    0,
                    10
                ],
                "name": "Account1",
                "screen_name": "account1"
            },
            {
                "id": 27822535,
                "id_str": "27822535",
                "indices": [
                    11,
                    18
                ],
                "name": "Account2",
                "screen_name": "account2"
            }
        ]
    },
    "favorite_count": 0,
    "favorited": false,
    "filter_level": "low",
    "geo": null,

我如何将关键实体的所有值 -> user_mentions -> screen_name 存储在变量、列表或其他内容中?我只是想存储它们并稍后做一些事情。

到目前为止,我得到了:

def on_data(self, data):
    # Twitter returns data in JSON format - we need to decode it first
    decoded = json.loads(data)
    #print(json.dumps(decoded, indent=4, sort_keys=True))
    tweet_id = decoded['id_str']
    username = decoded['user']['screen_name']
    text = decoded['text']
    is_reply = decoded['in_reply_to_status_id']
    mentions = decoded['entities']['user_mentions']['screen_name']

这给了我一个错误,因为它当然会返回多个 screen_name。

    mentions = decoded['entities']['user_mentions']['screen_name']
TypeError: list indices must be integers or slices, not str

标签: pythonjsonpython-3.x

解决方案


该错误为您提供了一个很好的提示。 decoded['entities']['user_mentions'] 是一个列表,因此您可以使用以下方法获取所有屏幕名称:

for name in decoded['entities']['user_mentions']:
    # name['screen_name'] now is the name you want
    print(name['screen_name'])

如果您想要所有屏幕名称的长字符串,或者做其他各种事情,您还可以使用列表功能,如 @Sushanth 注意到的那样。


推荐阅读