Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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#'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading