简体   繁体   English

SortedDict:按python中的值排序

[英]SortedDict: Sort by value in python

SortedDict is a class that inherits from dictionary and keeps elements sorted by key all the time. SortedDict是一个类,该类从dictionary继承,并且始终保持键对元素进行排序。 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: 我希望通过每个数组的第一个元素对它进行排序,以便获得如下排序的dict:

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. 我需要一种让函数访问sd本身中键值的方法。 Would this be possible? 这可能吗?

I believe you cannot order dictionaries. 我相信您不能订购字典。 If you want to maintain an ordering with the key, maybe go for an array of arrays with your key in the first or last position. 如果要保持键的顺序,则可以选择键位于第一个或最后一个位置的数组。 You can use the sorted function to sort the dictionary but it will not give you a dictionary object back in order 您可以使用sorted函数对字典进行排序,但不会按顺序返回字典对象

d = {0:[34, 67, 3],1:[12, 4, 9],2:[25, 3, 1]}
d_sorted = sorted(d.items(), key=lambda kv: kv[1][0])

which returns 哪个返回

[(1, [12, 4, 9]), (2, [25, 3, 1]), (0, [34, 67, 3])]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM