Home > Enterprise >  how I sort or sorted dictionary values that they are lists?
how I sort or sorted dictionary values that they are lists?

Time:12-26

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: {3: ['I','love'], 2: ['self.py!']}

CodePudding user response:

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

CodePudding user response:

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']}
  • Related