0

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!

solarenqu
  • 804
  • 4
  • 19
  • 44

2 Answers2

2

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}
jfaccioni
  • 7,099
  • 1
  • 9
  • 25
  • Ohh! That is what i wanted! :) Thank you so much! – solarenqu Sep 26 '19 at 13:55
  • as a note: dictionaries *do have order* in a way - [are dictionaries ordered in python 3.6?](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6/39980744) – Tomerikoo Sep 26 '19 at 13:57
  • Yep, in Python >= 3.6 insertion order is guaranteed (OP's question wouldn't make sense otherwise), but AFAIK you can't reorder an existing dictionary in-place. – jfaccioni Sep 26 '19 at 13:58
1

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()))}
Porada Kev
  • 503
  • 11
  • 24
  • It's not ok. The order dict must look like this: OrderedDict([(0, 200000), (1, 533800), (2, 858500), (3, 910800), (4, 1000000)]) So the value that belongs to key 0 must be lower then the value belongs to key 1 and so on.. – solarenqu Sep 26 '19 at 13:52
  • changed my answer – Porada Kev Sep 26 '19 at 13:57