Search code examples
pythonpython-3.xperformancesortingdictionary

Sort Dict by Values in Python 3.6+


I was looking for a method to sort a dictionary in Python with its values, after a few attempts, is what it comes:

a = {<populated dict...>}
a = {v: k for k, v in a.items()}
a = {v: k for k, v in sorted(a.items())}

This code seems to work, but I think it's poor for performance, is there a better way?


Solution

  • By default, the dictionary is sorted based on keys, but the sorted function takes a function as a parameter using which you can alter the behaviour for program.

    d={'a':6,'b':4,'k':3}
    print(sorted(d)) 
    
    sorted_by_values= sorted(d,key=lambda x:d[x])
    print(sorted_by_values)