uhoh
uhoh

Reputation: 3745

Sort a python dictionary by a specific function applied to its keys

Sorting dictionary with a numpy based function applied to its keys using np.argsort.

The following works but seems like too many steps; is there a simpler way?

Assume my final sorting function will be more complicated than the abstracted n/m shown here

import numpy as np

def get_sorted_dic(dictionary):

    keys = list(dictionary.keys())

    m, n = np.array(keys).T

    order = np.argsort(n/m).tolist()

    keyz = [keys[i] for i in order]

    return dict([(key, dictionary[key]) for key in keyz])

dic = {(7, 13): 'third', (9, 5): 'first', (27, 49): 'second'}

print(get_sorted_dic(dic))

which does return the correctly sorted dictionary {(9, 5): 'first', (27, 49): 'second', (7, 13): 'third'}

Upvotes: 0

Views: 56

Answers (2)

RoadRunner
RoadRunner

Reputation: 26315

You could also sort items() directly, then apply dict():

>>> dict(sorted(dic.items(), key=lambda x: x[0][1] / x[0][0]))
{(9, 5): 'first', (27, 49): 'second', (7, 13): 'third'}

Upvotes: 1

ywbaek
ywbaek

Reputation: 3031

You can just use sorted function:

dic = {(7, 13): 'third', (9, 5): 'first', (27, 49): 'second'}

dic_sorted = {k: dic[k] for k in sorted(dic.keys(), key=lambda t: t[1] / t[0])}
print(dic_sorted)
{(9, 5): 'first', (27, 49): 'second', (7, 13): 'third'}

Just replace lambda function with your sorting function.

Upvotes: 3

Related Questions