我有一个从数据库中两个字段读取的值字典:字符串字段和数字字段。字符串字段是唯一的,因此它是字典的关键字。
我可以按关键字排序,但如何根据值排序?
注意:我在这里读过堆栈溢出问题。如何根据字典的值对字典列表进行排序?并且可能会更改我的代码,使其具有字典列表,但由于我确实不需要字典列表,我想知道是否有更简单的解决方案来按升序或降序排序。
我有一个从数据库中两个字段读取的值字典:字符串字段和数字字段。字符串字段是唯一的,因此它是字典的关键字。
我可以按关键字排序,但如何根据值排序?
注意:我在这里读过堆栈溢出问题。如何根据字典的值对字典列表进行排序?并且可能会更改我的代码,使其具有字典列表,但由于我确实不需要字典列表,我想知道是否有更简单的解决方案来按升序或降序排序。
当前回答
简单如: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])
我写这篇详细的解释是为了说明人们通常所说的“我可以很容易地按关键字对字典进行排序,但我如何按值排序”——我认为最初的文章正试图解决这一问题。解决方案是根据这些值列出一些键,如上所示。
其他回答
从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中的实现细节。
除了使用内置模块等,我尝试手动解决它。。。
首先,我制作了一个函数,其任务是返回dict的每个项的最小值:
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}
嗯……我不知道哪一个是正确的,但这是我尝试过的。。。
此方法不使用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 ('=======================')
在最近的Python2.7中,我们有了新的OrderedDict类型,它可以记住添加项目的顺序。
>>> d = {"third": 3, "first": 1, "fourth": 4, "second": 2}
>>> for k, v in d.items():
... print "%s: %s" % (k, v)
...
second: 2
fourth: 4
third: 3
first: 1
>>> d
{'second': 2, 'fourth': 4, 'third': 3, 'first': 1}
要从原始字典创建新的有序字典,请按值排序:
>>> from collections import OrderedDict
>>> d_sorted_by_value = OrderedDict(sorted(d.items(), key=lambda x: x[1]))
OrderedDict的行为类似于普通dict:
>>> for k, v in d_sorted_by_value.items():
... print "%s: %s" % (k, v)
...
first: 1
second: 2
third: 3
fourth: 4
>>> d_sorted_by_value
OrderedDict([('first': 1), ('second': 2), ('third': 3), ('fourth': 4)])
使用字典中的ValueSortedDict:
from dicts.sorteddict import ValueSortedDict
d = {1: 2, 3: 4, 4:3, 2:1, 0:0}
sorted_dict = ValueSortedDict(d)
print sorted_dict.items()
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]