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?