0

Overall, I have a code which reads through a data file with data about countries which participated in the Olympics. This portion of code checks if in the year requested there are medallists from any countries and writes it in the dict if there are any. Basically, I am trying to count the amount of Gold, Silver and Bronze medals for each country in this year. That's why I've made a dictionary however for some reason "KeyError: 'Norway'" occurs, and I'm unsure how to fix that.

A bit more info: medals_dict is an empty dictionary. There is no dictionary full_country, full_country is just a text string

Here's the code:

    def total_medal_counter(year_in_data, full_country, medal):
    global year
    global medals_dict
    if year == year_in_data:
        if full_country in medals_dict:
            if medal in full_country:
                medals_dict[full_country][medal] = medals_dict[full_country][medal] + 1
                print(medals_dict)
        else:
            medals_dict[full_country][medal] = 1
            print(medals_dict)
  • 1
    Whenever you find yourself doing `if key in dict: dict[key] += 1 else: dict[key] = 0`, you can use [`defaultdict(int)`](https://stackoverflow.com/questions/5900578/how-does-collections-defaultdict-work). Same for creating new lists, sets, or any type of object when the key doesn't exist. – Reti43 Oct 14 '21 at 10:20

1 Answers1

2

You are checking

if full_country in medals_dict:

but have

else:
        medals_dict[full_country][medal] = 1

So when you come to that else statement, you are accessing medals_dict[full_country] without it existing, since you have never created that entry. You probably wanted

else:
    medals_dict[full_country] = {medal: 1}

Your inner if is also probably supposed to be

if medal in medals_dict[full_country]:

Full code:

def total_medal_counter(year_in_data, full_country, medal):
    global year
    global medals_dict
    if year == year_in_data:
        if full_country in medals_dict:
            if medal in medals_dict[full_country]:
                medals_dict[full_country][medal] = medals_dict[full_country][medal] + 1
                print(medals_dict)
        else:
            medals_dict[full_country] = {medal: 1}
            print(medals_dict)
FlyingTeller
  • 17,638
  • 3
  • 38
  • 53