【问题标题】:KeyError when appending to a Python dictionary with a string index使用字符串索引附加到 Python 字典时出现 KeyError
【发布时间】:2020-04-01 09:41:27
【问题描述】:

我收到以下错误:

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,顺便说一句),但显然还不够接近。

【问题讨论】:

  • 使用dict.get(key)

标签: python python-2.7 dictionary


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2017-08-22
    相关资源
    最近更新 更多