我有一个从数据库中两个字段读取的值字典:字符串字段和数字字段。字符串字段是唯一的,因此它是字典的关键字。

我可以按关键字排序,但如何根据值排序?

注意:我在这里读过堆栈溢出问题。如何根据字典的值对字典列表进行排序?并且可能会更改我的代码,使其具有字典列表,但由于我确实不需要字典列表,我想知道是否有更简单的解决方案来按升序或降序排序。


当前回答

与汉克·盖伊的回答大致相同:

sorted([(value,key) for (key,value) in mydict.items()])

或者根据John Fouchy的建议进行略微优化:

sorted((value,key) for (key,value) in mydict.items())

其他回答

此方法不使用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 ('=======================')
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

在Python 2.7中,只需执行以下操作:

from collections import OrderedDict
# regular unsorted dictionary
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

# dictionary sorted by key
OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

# dictionary sorted by value
OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

复制粘贴自:http://docs.python.org/dev/library/collections.html#ordereddict-示例和食谱

享受;-)

从Python 3.6开始,dict对象现在按插入顺序排序。这是Python 3.7规范中的正式版本。

>>> words = {"python": 2, "blah": 4, "alice": 3}
>>> dict(sorted(words.items(), key=lambda x: x[1]))
{'python': 2, 'alice': 3, 'blah': 4}

在此之前,您必须使用OrderedDict。

Python 3.7文档说明:

在3.7版中更改:字典顺序保证插入顺序该行为是CPython在3.6中的实现细节。

简单如:sorted(dict1,key=dict1.get)

嗯,实际上可以进行“按字典值排序”。最近,我不得不在代码高尔夫(堆栈溢出问题代码高尔夫:单词频率表)中这样做。简言之,问题是这样的:给定一个文本,计算每个单词遇到的频率,并显示一个按频率递减排序的顶级单词列表。

如果您构建一个字典,将单词作为关键字,将每个单词的出现次数作为值,则此处简化为:

from collections import defaultdict
d = defaultdict(int)
for w in text.split():
    d[w] += 1

然后,您可以得到一个单词列表,按使用频率排序,排序(d,key=d.get)-排序将使用单词出现的次数作为排序关键字,在字典关键字上迭代。

for w in sorted(d, key=d.get, reverse=True):
    print(w, d[w])

我写这篇详细的解释是为了说明人们通常所说的“我可以很容易地按关键字对字典进行排序,但我如何按值排序”——我认为最初的文章正试图解决这一问题。解决方案是根据这些值列出一些键,如上所示。