简体   繁体   中英

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

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

from collections import OrderedDict
OrderedDict(sorter(data))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM