How can I sort or sorted dictionary values that they are lists?

Question:

I got assigment to reverse the key and values in dictionary and I need to sort or sorted every values lists, any suggestions?
this is my code:

def inverse_dict(my_dict):
    my_inverted_dict = dict()
    for key, value in my_dict.items():
        my_inverted_dict.setdefault(value, list()).append(key)
    return my_inverted_dict
dict1 ={'love': 3, 'I': 3,  'self.py!': 2}
print(inverse_dict(dict1))

The output need to be like this: {3: ['I','love'], 2: ['self.py!']}
thanks (:

Asked By: neriya

||

Answers:

One simple method is to loop over all the values in the dict at the end and call sort on each list.

for v in my_inverted_dict.values():
    v.sort()
return my_inverted_dict
Answered By: Unmitigated

another approach might look like this:

from operator import itemgetter
from itertools import groupby

def inverse_dict(my_dict):
    return {k:[i for i,_ in g] for k,g in groupby(sorted(dict1.items(), key=itemgetter(1,0)),key=itemgetter(1))}

dict1 ={'love': 3, 'I': 3,  'self.py!': 2}
print(inverse_dict(dict1))  # {2: ['self.py!'], 3: ['I', 'love']}
Answered By: SergFSM
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.