【问题标题】:Getting a keyerror python when trying to add a new key to a Python dictionary尝试向 Python 字典添加新键时出现 keyerror python
【发布时间】:2022-01-22 13:16:43
【问题描述】:

在下一个代码中,当我尝试向字典添加新键时,我收到了 KeyError。

def tournamentWinner(competitions, results):
    record = {}
    winner = None
    for i in range(len(results)):
        if results[i] == 0:
            if record[competitions[i][1]] not in record:
                record[competitions[i][1]] = 3
            else:
                record[competitions[i][1]] += 3
        else:
            if record[competitions[i][0]] not in record:
                record[competitions[i][0]] = 3
            else:
                record[competitions[i][0]] += 3
    for element in record:
        if winner is None:
            winner = element
        if element > winner:
            winner = elemnt
    return winner

我收到了这个 KeyError:

Exception Detected: 
Traceback (most recent call last):
  File "/tester/program.py", line 7, in tournamentWinner
    if record[competitions[i][1]] not in record:
KeyError: 'C#'

【问题讨论】:

  • 您正在查看record[competitions[i][1]] 的值是否是记录的一部分。如果competitions[i][1] 在记录中,则不会。

标签: python python-3.x dictionary


【解决方案1】:

您收到该错误是因为在您使用 if-else 检查时,record 中不存在 competitions[i][1] 键。

您可以使用dict.get 方法解决此问题:

而不是这个 if-else:

if record[competitions[i][1]] not in record:
                record[competitions[i][1]] = 3
            else:
                record[competitions[i][1]] += 3

你可以使用

record[competitions[i][1]] = record.get(competitions[i][1], 0) + 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2018-05-27
    相关资源
    最近更新 更多