+ 2

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 ) ?

1st Oct 2018, 7:57 AM
sama baluom
sama baluom - avatar
6 ответов
+ 2
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()])
1st Oct 2018, 8:41 AM
HonFu
HonFu - avatar
+ 3
I think dictionaries uses hash tables so there is no any order in them. Your both examples should be equal.
1st Oct 2018, 8:35 AM
Bebida Roja
Bebida Roja - avatar
+ 3
Beside other users comment, i suggest to see here https://docs.python.org/3.5/library/collections.html#collections.OrderedDict
1st Oct 2018, 9:28 AM
KrOW
KrOW - avatar
+ 3
thank you all☺
1st Oct 2018, 10:07 AM
sama baluom
sama baluom - avatar
+ 1
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?
1st Oct 2018, 9:39 AM
HonFu
HonFu - avatar
+ 1
@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)
1st Oct 2018, 9:57 AM
KrOW
KrOW - avatar