简体   繁体   中英

Python order a dict by keys and values

I have a python dict that i want to order by keys and values too but i only can order it by values:

dict_to_sort = {0: 200000, 1: 858500, 2: 533800, 3: 910800, 4: 1000000}
print(dict_to_sort)
{0: 200000, 1: 858500, 2: 533800, 3: 910800, 4: 1000000}

dict_sorted = sorted(dict_to_sort.items(), key=lambda kv: kv[1])
dict_sorted = collections.OrderedDict(dict_sorted)
print(dict_sorted)
OrderedDict([(0, 200000), (2, 533800), (1, 858500), (3, 910800), (4, 1000000)])

So as you can see, the dict_sorted has been ordered by values, but i would like to order the keys too.

The dict ordered must be looks like this:

OrderedDict([(0, 200000), (1, 533800), (2, 858500), (3, 910800), (4, 1000000)])

Can you help me?

Thank you!

Your question is phrased wrong. Your desired result isn't ordering the dictionary by keys/values (which you actually can't do since dictionaries have no order). You actually want a new dictionary whose key:value pairs are the pairs from two ordered sequences corresponding to the independent sorting of your original dictionary's keys and values.

This code results in what you want:

>>> dict_to_sort = {0: 200000, 1: 858500, 2: 533800, 3: 910800, 4: 1000000}
>>> sorted_keys = sorted(dict_to_sort.keys()
>>> sorted_values = sorted(dict_to_sort.values())
>>> dict_sorted = {k:v for k, v in zip(sorted_keys, sorted_values)}
>>> dict_sorted
{0: 200000, 1: 533800, 2: 858500, 3: 910800, 4: 1000000}

UPDATED

You can do that with this simple for loop:

dict_sorted = {}
for i, ii in enumerate(sorted(dict_to_sort.values())):
    dict_sorted[i] = ii
print(dict_sorted)

It can be also done as a dict comprehension:

dict_sorted = {i:ii for i, ii in enumerate(sorted(dict_to_sort.values()))}

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