python - 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
解决方案
该错误为您提供了一个很好的提示。
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 注意到的那样。
推荐阅读
- idris - 在 Idris 中显示类型或 typeOf?
- algorithm - 计算浮点值以将整数乘以产生小于 1 的最大数
- reactjs - 超过最大更新深度当我尝试创建登录表单时
- python - 当每个 csv 有多个公共列时,如何最好地将多个 csv 读入单个数据帧
- rust - 如何在调用 format! 时允许未实现 Display 的未使用命名参数!
- regex - 总是有一个 perl 正则表达式修饰符来进行文字匹配吗?
- sorting - 如果分号,则在外部 awk 调用中排序字段分隔符问题
- python - 如何使用 Python 连续读取基于 Linux 的操作系统的 CPU 温度?
- php - 使用 laravel mix 将 Datatables JS 逻辑放在哪里?
- java - 如何订购 AOP 方面和 MVC 拦截器?