Q: Inverting dictionary in Python not yielding results I'm doing an assignment that asks me to create a dictionary and then invert it based on "Think Python" book function. The function has to invert my dictionary and turn each list item into separated keys.
I created a dictionary that shows similar soccer players for the sake of the assignment however I thought that my function should be returning the inverted dictionary by now but it isn't.
    def soccer():
    splayers = dict()
splayers = {'Ronaldo': 'Messi', 'Buffon': 'Courtois', 'Mbappe': 'Vinicius'}
def invert_dict(splayers):
     inverse = dict()
     for key in splayers:
          val = splayers[key]
          if val not in inverse:
               inverse[val] = [key]
          else:
               inverse[val].append(key)
     return inverse

Thoughts? Thanks!

A: You can make this somewhat simpler using the setdefault() method.
splayers = {'Ronaldo': 'Messi', 'Buffon': 'Courtois', 'Mbappe': 'Vinicius'}
inverted = dict()
for k,v in splayers.items():
    inverted.setdefault(v,[]).append(k)

You could also do it on a single line using groupby() from itertools but it will be less efficient and not as legible:
from itertools import groupby
inverted = { key:list(values) for key,values in groupby(sorted(splayers),lambda x:splayers[x]) }


A: Using dict comprehension:
>> splayers = {'Ronaldo': 'Messi', 'Buffon': 'Courtois', 'Mbappe': 'Vinicius'}
>> splayers_inv = {value: key for key, value in splayers.items()}
>> splayers_inv
{'Courtois': 'Buffon', 'Messi': 'Ronaldo', 'Vinicius': 'Mbappe'}

