Yuri
Yuri

Reputation: 35

keep keys of dictionary while sorting the values

I have got the following sort function:

orderedX = np.array(list(to_sort.values()))\
[np.array(list(to_sort.values())).argmax(axis=1).argsort(), :]

but I want to change it such that, orderedX becomes a dictionary with the items of to_sort, instead of just a list of its values. So the way it is sorted is correct, but is there someway I can also keep track of the keys while doing this?

to_sort is a dict with keys and values, where each value is a np.array

Upvotes: 0

Views: 1628

Answers (1)

Jeronimo
Jeronimo

Reputation: 2387

The problem with dictionaries is that they generally don't preserve order. Even with Python 3.6's changes to the implementation of dict, the docs say that "The order-preserving aspect of this new implementation [...] should not be relied upon". Here's another SO question where this is explained in detail, look especially for Martijn Pieters' answer.

That being said, there's still collections.OrdererDict that does have order preservation. Here's how you create one with the desired sorting from your data. Note that I tried to simplify the sort algo a little bit, which, as far as I understood it, sorts by the maximum of the array in to_sort's values:

from collections import OrderedDict
ordered = OrderedDict(sorted(to_sort.items(), key=lambda item:np.max(item[1])))

Iterating over it like this will give you both keys and values with values in sorted order:

for key, value in ordered.items():
    print(key, value)

Upvotes: 1

Related Questions