如何按值对字典进行排序?

3414

我有一个从数据库中读取的键值对字典:一个字符串字段和一个数字字段。字符串字段是唯一的,所以它是字典的键。

我可以按照键排序,但是如何基于值排序呢?

注意:我已经在Stack Overflow上阅读了这里的问题:How do I sort a list of dictionaries by a value of the dictionary?,并且可能可以更改我的代码以使用字典列表,但由于我实际上不需要字典列表,我想知道是否有更简单的解决方案来升序或降序排序。


9
字典数据结构没有固有的顺序。虽然可以遍历它,但不能保证遍历的顺序是特定的。这是设计上的考虑,因此最好使用另一种数据结构来表示。 - Daishiman
135
"sorted()" 函数可以用于字典(并返回已排序的键列表),因此我认为他知道这一点。如果不了解其程序,就告诉别人他们使用了错误的数据结构是荒谬的。如果你需要90%的时间快速查找,则可能需要使用字典。 - bobpaul
这里清晰简洁地介绍了排序字典的三种输出方式(键、值、两者):https://dev59.com/nGQn5IYBdhLWcg3wg3aR - JStrahl
2
@Daishiman 基类可能没有排序,但是OrderedDict当然是有序的。 - Taylor D. Edmiston
1
在Python 3.6+中,字典保留插入顺序。当然,这并不意味着可以按值对它们进行排序,但另一方面,不能再说“字典数据结构没有固有的顺序”了。 - Konrad Kocik
34个回答

6
months = {"January": 31, "February": 28, "March": 31, "April": 30, "May": 31,
          "June": 30, "July": 31, "August": 31, "September": 30, "October": 31,
          "November": 30, "December": 31}

def mykey(t):
    """ Customize your sorting logic using this function.  The parameter to
    this function is a tuple.  Comment/uncomment the return statements to test
    different logics.
    """
    return t[1]              # sort by number of days in the month
    #return t[1], t[0]       # sort by number of days, then by month name
    #return len(t[0])        # sort by length of month name
    #return t[0][-1]         # sort by last character of month name


# Since a dictionary can't be sorted by value, what you can do is to convert
# it into a list of tuples with tuple length 2.
# You can then do custom sorts by passing your own function to sorted().
months_as_list = sorted(months.items(), key=mykey, reverse=False)

for month in months_as_list:
    print month

1
除了使用内置模块等,我尝试手动解决它... 首先,我创建了一个函数,其工作是返回字典中每个项的最小值:
def returnminDict(_dct):
    dict_items = _dct.items()
    list_items = list(dict_items)
    init_items = list_items[0]
    for i in range(len(list_items)):
        if list_items[i][1] > init_items[1]:
           continue
        else:
           init_items = list_items[i]
    return init_items

其次,现在我们有一个返回具有最小值的项的函数。然后我创建一个新的字典并循环遍历该字典:
def SelectDictSort(_dct):
    new_dict = {}
    while _dct:
        mindict = returnminDict(_dct)
        new_dict.update(dict((mindict,)))
        _dct.pop(mindict[0])
    return new_dict

我尝试使用SelectDictSort({2: 5, 5: 1, 4: 3, 1: 1, 0: 1, 9: 2, 8: 2})。它将返回:

{0: 1, 1: 1, 5: 1, 8: 2, 9: 2, 4: 3, 2: 5}

嗯...我不知道哪个是正确的,但这是我尝试过的...


0
使用Python 3.2版本:
x = {"b":4, "a":3, "c":1}
for i in sorted(x.values()):
    print(list(x.keys())[list(x.values()).index(i)])

-2

该方法不使用lambda,并可在Python 3.6上正常工作:

 # sort dictionary by value
d = {'a1': 'fsdfds', 'g5': 'aa3432ff', 'ca':'zz23432'}
def getkeybyvalue(d,i):
    for k, v in d.items():
        if v == i:
            return (k)

sortvaluelist = sorted(d.values())

# In >> Python 3.6+ << the INSERTION-ORDER of a dict is preserved. That is,
# when creating a NEW dictionary and filling it 'in sorted order',
# that order will be maintained.
sortresult ={}
for i1 in sortvaluelist:   
    key = getkeybyvalue(d,i1)
    sortresult[key] = i1
print ('=====sort by value=====')
print (sortresult)
print ('=======================')

3
我可以翻译为:请问您能否添加一些关于您的源代码的背景信息?仅有代码的回答很难理解。如果您在帖子中添加更多信息,将有助于提问者和未来的读者。 - HDJEMAI
2
这是一个非常低效的解决方案,使用线性搜索和全部。 - Jean-François Fabre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接