So I have a dictionary which needs to be sorted by values. I sort them with below Python3 function which returns sorted data as a list of tuples.
def sorter(data):
return sorted(data.items(), key=lambda kv: kv[1], reverse=True)
It sorts the data perfectly, but when I convert this list back to dictionary by
dict(sorter(data))
It loses the order and returns a dictionary in a completely random order. What am I missing here?
Dictionaries in Python are implemented as hash tables, which are inherently unordered – or rather, they are ordered arbitrarily and may change their order upon any modification.
This was changed in Python 3.7, where dictionaries keep their insertion order. But relying on this will make your code less portable.
Use
OrderedDictif you want to keep the ordering on all Python versions: