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

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

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


当前回答

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

其他回答

简单如: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])

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

此方法不使用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 ('=======================')
from django.utils.datastructures import SortedDict

def sortedDictByKey(self,data):
    """Sorted dictionary order by key"""
    sortedDict = SortedDict()
    if data:
        if isinstance(data, dict):
            sortedKey = sorted(data.keys())
            for k in sortedKey:
                sortedDict[k] = data[k]
    return sortedDict

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

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

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

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

另一个答案中提到的集合解决方案绝对是极好的,因为您在键和值之间保留了一种联系,这在字典中是极其重要的。

我不同意另一个答案中的第一选择,因为它会扔掉钥匙。

我使用了上面提到的解决方案(代码如下所示),并保留了对键和值的访问权,在我的情况下,排序是对值进行的,但重要的是对值排序后的键排序。

from collections import Counter

x = {'hello':1, 'python':5, 'world':3}
c=Counter(x)
print( c.most_common() )


>> [('python', 5), ('world', 3), ('hello', 1)]