1

I am trying to reverse a dictionary by flipping the values with the keys

The output i got: {3: 'love', 2: 'self.py!'}

the output I want: {3: ['I', 'love'], 2: ['self.py']}

my code:

def inverse_dict(my_dict):
    inv_dict = {v: k for k, v in my_dict.items()}
    print(inv_dict)


def main():
    course_dict = {'I': 3, 'love': 3, 'self.py!': 2}
    inverse_dict(course_dict)


if __name__ == "__main__":
    main()

It's like took away the key and the value 'I': 3 someone knows why?

4 Answers4

2

You can use the dictionary method setdefault for this. It works like this:
If the key is in the dictionary, return its value. If not, insert the key with a value of default(empty list in this case) and return default(list).

course_dict = {'I': 3, 'love': 3, 'self.py!': 2}
new_dict = {}
for key, value in course_dict.items():
    new_dict.setdefault(value, []).append(key)

print(new_dict)

Output:

{3: ['I', 'love'], 2: ['self.py!']}
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
2

Not sure how you'd do this with a dict comprehension but using a default dict should be trivial

from collections import defaultdict

inv_dict = defaultdict(list)
for k,v in course_dict.items():
    inv_dict[v].append(k)
Sayse
  • 42,633
  • 14
  • 77
  • 146
1

This code, copied from https://www.geeksforgeeks.org/python-program-to-swap-keys-and-values-in-dictionary/ (Method #2) checks for multiple values, like in your output

old_dict = {'A': 67, 'B': 23, 'C': 45, 'E': 12, 'F': 69, 'G': 67, 'H': 23} 
  
new_dict = {} 
for key, value in old_dict.items(): 
   if value in new_dict: 
       new_dict[value].append(key) 
   else: 
       new_dict[value]=[key] 
  
ralf htp
  • 9,149
  • 4
  • 22
  • 34
0

I think the title of your question does not reflect exactly what you want to do according to the expected output you provided.

Indeed, instead of reversing / inverting a dictionary you want to group the keys per values.

This should do the job (I did not change the name of the function but you might want to since it can be misleading):

from collections import defaultdict

def inverse_dict(input_dict):
    inversed = defaultdict(list)
    for k, v in input_dict.items():
       inversed[v].append(k)
    
    return dict(inversed)

The output is the following:

inverse_dict({'I': 3, 'love': 3, 'self.py!': 2})
>>> {3: ['I', 'love'], 2: ['self.py!']}