how can I sort dictionary by value without using lambda or use import "something"?

I have dictionary d1={ 2:9, 5:4, 9:1}, what can I do to get d1={9:1, 5:4, 2:9} ,(sort by value ) ?

10/1/2018 7:57:01 AM

sama baluom

7 Answers

New Answer


Dictionaries in Python are not meant to be sorted, so for example giving a sorted output will always involve making at least a temporary list version of it, like: print(*sorted(d1.values())) Would that be good enough? If not... Do you access the dictionary by key anywhere in your code? If not, you could instead make a list of tuples and sort that, like: d1 = [(2, 9), (5, 4), (9,1)] If you want to sort this by the second value of a tuple, you'd need a tiny lambda though. ;) d1. sort(key=lambda element: element[1]) If you insist on avoiding lambda, you can just put the 'value' first in the tuple, because the default for sorting sequences is the first element (if equal: next, and so on). To quickly get your dictionary into this format you could write: d1 = sorted([x[::-1] for x in d1.items()]) Or: d1 = sorted([(b, a) for (a, b) in d1.items()])


Doesn't work in all circumstances but it works in yours: https://code.sololearn.com/cp2zHGl98nWT/?ref=app


I think dictionaries uses hash tables so there is no any order in them. Your both examples should be equal.


Beside other users comment, i suggest to see here https://docs.python.org/3.5/library/collections.html#collections.OrderedDict


thank you all☺


KrOW, interesting, I haven't used these yet! I have a question: These dicts seem to sort by order of entry, right? So if you want your dictionary sorted, you'd have to pre-sort it anyway, like it's demonstrated in the doc, using 'sorted(...)' . And since every new entry will be entered at the end of the OrderedDict, will that not force you to re-sort the thing via 'sorted' every time you change it?


@HonFu Yes. Yes. And yes :). Every time that you add some key, this is appended to last position then if you want apply sort, you have to rebuild the ordered dict (its better use it only for fixed items)