简体   繁体   中英

How to sort dictionary in numeric order?

I have an output like the following dictionary.

dict = {"1":df1,"10":df2,"11":df11,"4":df4,'5':df5,"6":df6}

I want to rearrange the order of the dictionary by the numeric order of the keys as below.

dict = {1":df1,"4":df4,'5':df5,"6":df6,"10":df2,"11":df11}

I tried

OrderedDict(sorted(dict .items()))

However, this did not work. Does anyone know how to do that?

Thanks.

THe problem is that strings are sorted lexicographically . So that means that '1' < '10' < '2' . We can however solve that by making a mapping to int , like:

OrderedDict(sorted(mydict.items()))

this will yield a result that looks like:

>>> OrderedDict(sorted(mydict.items(), key=lambda t: int(t[0])))
OrderedDict([('1', df1), ('4', df4), ('5', df5), ('6', df6), ('10', df2), ('11', df11)])

Note that since , dictionaries use the insertion order, and hence there is no need to use an OrderedDict . As @chepner says, there is still a subtle difference since " the order of the keys in an OrderedDict affect equality , but not in a dict. ".

Note : please do not use dict as variable name, since this will override the reference to the dict class.

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