首页 > 解决方案 > 使用字符串索引附加到 Python 字典时出现 KeyError

问题描述

我收到以下错误:

键错误:'sat'

在我的 Python 脚本中如下:

balls = {}
balls_count = 0

for entry_content in latest_results_soup.find_all('img',vspace='12'):

    if balls_count < 5:
        draw_day = 'sat'
    else:
        draw_day = 'wed'

    balls[draw_day].append(int(entry_content['src'].rsplit('/', 1)[-1].split('.')[0]))

    balls_count += 1

我正在寻找的是一个字典或列表来进一步解析,其结构类似于:

balls['sat'] = [5, 7, 20, 28, 30]
balls['wed'] = [1, 6, 9, 19, 20]

我觉得我很接近(Python n00b,顺便说一句),但显然不够接近。

标签: pythonpython-2.7dictionary

解决方案


我认为您应该在设置值或附加值之前提供satand键。wed

balls = {'sat': [], 'wed': []}

推荐阅读