Home > Mobile >  Getting a keyerror python when trying to add a new key to a Python dictionary
Getting a keyerror python when trying to add a new key to a Python dictionary

Time:12-21

In the next code, I'm getting a KeyError when I'm trying to add a new key to a dictionary.

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

I am getting this 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#'

CodePudding user response:

You're getting that error because competitions[i][1] key doesn't exist in record at the time you check for it with if-else.

You can get around this problem by using dict.get method:

Instead of this if-else:

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

you can use

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