python - 字典中存在键时引发 KeyError
问题描述
我有一段代码应该喷射一个 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()
输出消息:
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
(或同等)时,您应该始终做的第一件事是打印密钥所在的整个内容。您使用什么语言、数据来自哪里或其他任何内容都没有关系。上述解决方案(或等效方案)可以反复使用,唯一真正的变化是:如果您不在循环中,请摆脱中断/继续的东西。您可能是 StackOverflow 上第 1000 万人问“我的数据有什么问题?”,但从不费心打印自己的数据来查看。
想象一下,如果您不问这个问题并复制/粘贴所有代码,而是在分配print(media)
之前x
简单地编写(暂时的快速而肮脏的方式),那么您将节省多少时间。不要把它当作私人的。25 年前,我犯了同样的错误,但没有人可以问,一直犯错误,直到我意识到在问题之前打印该死的东西:D。最终我学会了像上面的代码那样处理问题。给你代码是一条鱼。给你这个技巧教你如何钓鱼。
推荐阅读
- java - 如何使用 jmap 从 Kubernetes Pod 获取 Java 堆转储?
- vb.net - 从表单中动态删除控件
- api - Sheets API Glitch 将数字舍入到 15 个有效数字 (Gspread)
- python - 如何从 message.content 中删除字符?
- html - 来自 2 个不同来源的视频替代品
- lua - 如何获得与另一个号码匹配的号码
- wso2 - 如何使用 Analytics 版本 3.2.0 配置 WSO2 API Manager 版本 4.0.0?
- reactjs - 使用效果未按预期调用
- html - 原子中的未知属性“网格模板列”
- javascript - 有条件地显示/隐藏项目