简体   繁体   English

附加到带有字符串索引的 Python 字典时出现 KeyError

[英]KeyError when appending to a Python dictionary with a string index

I am getting the following error:我收到以下错误:

KeyError: 'sat' KeyError: 'sat'

in my Python script as below:在我的 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

What i'm looking for is either a dict or list to parse further down which has a structure something like:我正在寻找的是一个 dict 或列表来进一步解析,其结构类似于:

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

I feel like I am close (Python n00b, BTW) but clearly not close enough.我觉得我很接近(Python n00b,顺便说一句),但显然还不够接近。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM