簡體   English   中英

字典中存在鍵時引發 KeyError

[英]KeyError is raised when key exists in dictionary

我有一段代碼應該噴射一個 json 輸入,並使用 for 循環將我放置在數據庫中的行中的數據分開。 當我嘗試從字典中獲取一個值時,它會給我一個錯誤,但是如果我嘗試在不使用循環的情況下訪問該值,它會起作用。

from api import DataBase2
import json

db = DataBase2.DataBase2('../database/db1.json')
json_file = json.load(open('yes.txt', 'r', encoding='utf-8'))
#sectional_items[0].layout_content.two_by_two_item.channel.media.media_type
for sectional_item in json_file['sectional_items']:
    medias = []
    if 'two_by_two_item' in sectional_item['layout_content']:
        medias.append(sectional_item['layout_content']['two_by_two_item']['channel']['media'])
    for fill_media in sectional_item['layout_content']['fill_items']:
        medias.append(fill_media)
    for media in medias:
        x = media['id']
        print(x)
        print(type(x))
        x = media.get('id')
        print(x)
        print(type(x))
        if media['media_type'] != 1:
            continue
        best_photo = ''
        best_photo_height = 0
        best_photo_width = 0
        for candidate in media['image_versions2']['candidates']:
            if candidate['height'] > best_photo_height or candidate['width'] > best_photo_width:
                best_photo_height = candidate['height']
                best_photo_width = candidate['width']
                best_photo = candidate['url']
                base = [media['id'], media['device_timestamp'], media['media_type'], media['code'], best_photo,
                        media['image_versions2']['candidates'][2], media['user']['username'], media['comment_count'],
                        media['like_count'],
                        media['caption']['text']]
                db.create_row('got_from_ig', 'media', base)
db.show_table('got_from_ig', 'media')
db.save()

Output 消息:

2359453249886770269_10139873678
2359453249886770269_10139873678
2359453249886770269_10139873678

錯誤信息:

Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/scraper/api/yes.py", line 14, in <module>
    x = media['id']
KeyError: 'id'

你確定每個media都有一個id嗎? 看起來你只是在打印 id 直到它們不再存在。 您應該處理錯誤並打印結果,以便查看包含的媒體並得出解決方案。

#temporary func for debugging purposes
def debug_print(baddata, msg='bad data'):
    #this line just makes it easier to read
    itemized = '\n'.join([f'\t{k}:{v}' for k, v in baddata.items()])
    print(f'Problem: {msg}\n{itemized}')
    return input('(c)ontinue else break? ')


for media in medias:
    try:
        #replace this comment with your loop code and catch all/any key errors
    except KeyError as err:
        if debug_print(media, str(err)) == 'c':
            continue
        else:
            break

專業提示:當您收到KeyError (或等效項KeyError時,您應該始終做的第一件事是打印密鑰所在的整個內容。您使用什么語言、數據來自哪里或其他任何內容都沒有關系。 上述解決方案(或等效方案)可以反復使用,唯一真正的變化是:如果您不在循環中,請擺脫中斷/繼續的東西。 您可能是 StackOverflow 上第 1000 萬人問“我的數據有什么問題?”,但從不費心打印自己的數據來查看。

想象一下,如果您不問這個問題並復制/粘貼所有代碼,而是在分配x之前簡單地編寫print(media) (臨時的快速而骯臟的方式),那么您將節省多少時間。 不要把它當作私人的。 25 年前,我犯了同樣的錯誤,但沒有人可以問,並且一直在犯錯誤,直到我意識到在問題之前打印該死的東西:D。 最終我學會了像上面的代碼那樣處理問題。 給你代碼是一條魚。 給你這個技巧教你如何釣魚。

sectional_item['layout_content']['two_by_two_item']['channel']['media']持有的值是一個帶有一些未知鍵的字典。 'id' 不是這些鍵之一。

嘗試在您的錯誤點之前執行此操作

for key in media.keys():
    print(key)
    print(media[key])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM