字典的更新方法-Python

2 投票
5 回答
700 浏览
提问于 2025-04-16 08:17

我写了一段代码,试图根据字典里的值来排序,而不是根据键。

""" This module sorts a dictionary based on the values of the keys"""

adict={1:1,2:2,5:1,10:2,44:3,67:2} #adict is an input dictionary 
items=adict.items()## converts the dictionary into a list of tuples

##print items

list_value_key=[ [d[1],d[0]] for d in items] """Interchanges the position of the 
                                                key and the values"""
list_value_key.sort()
print list_value_key

key_list=[ list_value_key[i][1] for i in range(0,len(list_value_key))]

print key_list  ## list of keys sorted on the basis of values 

sorted_adict={}

*for key in key_list:
    sorted_adict.update({key:adict[key]})
    print key,adict[key]

print sorted_adict*

所以当我打印 key_list 的时候,我得到了预期的结果。但是在代码的最后一部分,我尝试更新字典时,顺序却不是我想要的。下面是我得到的结果。我不太明白为什么“update”方法没有按预期工作。任何帮助或建议都很感谢。

结果:

sorted_adict={1: 1, 2: 2, 67: 2, 5: 1, 10: 2, 44: 3} 

5 个回答

2

别那样排序。

import operator
adict={1:1,2:2,5:1,10:2,44:3,67:2}
sorted_adict = sorted(adict.iteritems(), key=operator.itemgetter(1))
2

如果你需要一个能保持顺序的字典,可以使用一个叫做 OrderedDict 的类,它在 collections模块里。你可以参考那个页面上的方法来对字典进行排序,并创建一个新的 OrderedDict,这样就能保持排序的顺序。OrderedDict 类在 Python 2.7 或 3.1 版本中都可以使用。

3

Python中的字典,不管你怎么往里添加内容,都是没有顺序的。这是哈希表的特点。

所以,你可以考虑单独保存一个按顺序排列的键的列表,像这样:[ 5, 1, 44, ...]

这样的话,你以后就可以按照顺序访问你的字典了。

撰写回答