Losing sort order in python dictionary after converting from list of tuples

1.6k views Asked by At

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?

2

There are 2 answers

0
Thomas On BEST ANSWER

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 OrderedDict if you want to keep the ordering on all Python versions:

from collections import OrderedDict
OrderedDict(sorter(data))
0
AKX On

As the comments say, dictionaries aren't ordered (until Python 3.7).

If you need an ordered dict, use the aptly named collections.OrderedDict.

import collections

def sorter(data):
    return sorted(data.items(), key=lambda kv: kv[1], reverse=True)

d = collections.OrderedDict(sorter(data))