How to change the key and value of a dictionary

Viewed 75

So I've got the following code, and what I want to do is take every second value of the inputted tuple, and save it to a dictionary as the dict.key, and the dict.value set at first to 0. After that I want to go over the saved dictionary and for every time this dict.key occurs in the tuple I want to put the count of it in the dict.value. The code currently gives me an error.

def movie_awards(results):
    """
    I want to ignore every first value of the tuple
    """
    results = list(results)
    
    answer = {x[1]:0 for x in results}
    
    for x in results:
        answer[x[1]] = answer[x] + 1
    
    print(answer)

result = {("Best Picture", "Parasite"),\
          ("Best Actor", "Joker"),\
          ("Best Actress", "Judy"),\
          ("Best Sound Editing", "Ford v Ferrari"),\
          ("Best Sound Editing", "1917"),\
          ("Best Original Score", "Joker"),\
          ("Best Costume Design", "Little Women"),\
          ("Best Visual Effects", "Little Women"),\
          ("Best Director", "Parasite")}
3 Answers

Simply add the number using +=:

for x in results:
    answer[x[1]] += 1
    
print(answer)

Doing:

answer[x]

python is trying to fetch the key:value pair whose key is ('Best Original Score', 'Joker'). Since, it doesn't exist, a key error is raised.

You can also just use collections.Counter:

from collections import Counter

def movie_awards(results):
    return Counter(x[1] for x in results)

You could use a Counter:

from collections import Counter
c = Counter([t[1] for t in result])

>>> Counter({'Joker': 2, 'Parasite': 2, 'Little Women': 2, '1917': 1, 'Ford v Ferrari': 1, 'Judy': 1})
Related