1

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!

Bruno
  • 37
  • 4
  • 1
    Please format the code. Although, it doesn't look like you are actually calling your function anywhere – juanpa.arrivillaga Mar 19 '19 at 23:33
  • Possible duplicate of [Python reverse / invert a mapping](https://stackoverflow.com/questions/483666/python-reverse-invert-a-mapping) – Leonid Mar 19 '19 at 23:34

2 Answers2

1

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]) }
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

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'}
Daniel Labbe
  • 1,979
  • 3
  • 15
  • 20
  • If you read his code, he needs to handle the case where two players have the same last name by storing each first name as a list and appending to that list. – Boris Verkhovskiy Mar 20 '19 at 00:36