试图访问嵌套字典中的键值对:我哪里出错了?

2024-06-07 19:44:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新手。提前感谢您的耐心等待

我在Pandas中使用请求从API获取信息。以下是API结果:

{
"data": [
{
"all_awardings": [],
"allow_live_comments": false,
"author": "qu1et1",
"author_flair_css_class": null,
"author_flair_richtext": [],
"author_flair_text": null,
"author_flair_type": "text",
"author_fullname": "t2_will3i",
"author_patreon_flair": false,
"author_premium": false,
"awarders": [],
"can_mod_post": false,
"contest_mode": false,
"created_utc": 1577837075,
"domain": "open.spotify.com",
"full_link": "https://www.reddit.com/r/SpotifyPlaylists/comments/eib232/instant_addiction_jan_2020_update_your_selective/",
"gildings": {},
"id": "eib232",
"is_crosspostable": true,
"is_meta": false,
"is_original_content": false,
"is_reddit_media_domain": false,
"is_robot_indexable": true,
"is_self": false,
"is_video": false,
"link_flair_background_color": "",
"link_flair_richtext": [],
"link_flair_template_id": "933b36a2-d08e-11e8-883e-0e5f4502fa8a",
"link_flair_text": "Various",
"link_flair_text_color": "dark",
"link_flair_type": "richtext",
"locked": false,
"media": {
"oembed": {
"description": "We and our partners use cookies to personalize your experience, to show you ads based on your interests, and for measurement and analytics purposes. By using our website and our services, you agree to our use of cookies as described in our Cookie Policy.",
"height": 380,

我正在尝试获取“描述”键的内容。我试过:

data = getPushshiftData(after,last_epoch)
for post in data:
description = post[media][oembed]["description"]

因为媒体和oembed是字典,所以我不会引用它们

我得到了一个不可修复的类型:“dict”错误。有人能帮我看看哪里出了问题吗

编辑:我试着把媒体和oembed放在引号里,它给了我一个“媒体”的关键错误

while int(after) < last_epoch:
data = getPushshiftData(after,last_epoch)

for post in data:
    tmp_time = post['created_utc']
    timestamps.append(tmp_time)
    tmp_id = post['id']
    post_ids.append(tmp_id)
    tmp_full_link = post['full_link']
    full_link.append(tmp_full_link)
    
   
    tmp_description = (post['media']['oembed']['description']) #error
  

Tags: textidfalsedataislinkourdescription
1条回答
网友
1楼 · 发布于 2024-06-07 19:44:03

您只需要使用引号访问它,我将您的输出JSON保存在一个文件中,并使用json.load将其读入dict:

with open('1.json', 'r+') as f:
    data = json.load(f)

for rec in data['data']:
    print(rec['media']['oembed']['description'])

输出:

We and our partners use cookies to personalize your experience, to show you ads based on your interests, and for measurement and analytics purposes. By using our website and our services, you agree to our use of cookies as described in our Cookie Policy.

相关问题 更多 >

    热门问题