0

SortedDict is a class that inherits from dictionary and keeps elements sorted by key all the time. We can also specify for it to sort by some function of the key as follows.

def func(x):
    return -x

sd = SortedDict(func)

However, I would like to have it sort by values of the dictionary. For example:

d = {0:[34, 67, 3],1:[12, 4, 9],2:[25, 3, 1]}

I want this to be sorted by the first element of each array, so that I have a sorted dict as follows:

sd = {1:[12, 4, 9],2:[25, 3, 1],0:[34, 67, 3]}

Is there a way for me to do it? If I do the following:

def func(x):
   return d[x][0]

this is not a permanant solution, because, if I update my sorted dictionary:

sd.update({4:[6,5,9]})

I get a key error from the original dictionary.

I need a way for the function to access the value of the key in sd itself. Would this be possible?

Mahathi Vempati
  • 1,238
  • 1
  • 12
  • 33
  • Is there any particular reason for keeping the array sorted? – DYZ Sep 10 '19 at 06:26
  • See https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value - you could maintain an OrderedDict if you want instead of just building and returning one whenever needed, but I believe you would have to rebuild it on every insert. – Patrick Fay Sep 10 '19 at 06:27

0 Answers0