Python字典的更新方法

Python字典的更新方法,python,Python,我编写了一个代码,它试图使用值而不是键对字典进行排序 """ 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 li

我编写了一个代码,它试图使用值而不是键对字典进行排序

""" 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时,我得到了预期的答案,但是对于我尝试更新字典的代码的最后一部分,顺序不是它应该的顺序。以下是获得的结果。我不知道为什么更新方法不起作用。感谢您的帮助或指点

结果:

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

Python字典,无论您如何插入它们,都是无序的。这通常是哈希表的性质

相反,您可能应该按照键的值的顺序或排序来保存键列表,例如:[5,1,44,…]

这样,您可以在以后按排序顺序访问词典。

不要这样排序

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

要对措辞进行排序,您还可以使用:

adict={1:1,2:2,5:1,10:2,44:3,67:2}
k = adict.keys()
k.sort(cmp=lambda k1,k2: cmp(adict[k1],adict[k2]))

顺便说一句,在那之后再使用字典是没有用的,因为dict中没有顺序,它们只是映射类型-您可以有不同类型的键,它们是不可比较的。

如果您需要一个保持顺序的字典,在字典中有一个名为OrderedDict的类。您可以使用该页面上的配方对字典进行排序,并创建保留排序顺序的新OrderedICT。OrderedDict类在Python 2.7或3.1中可用。

一个问题是普通字典无法排序,因为它们是在内部实现的。Python2.7和3.1在其模块中添加了一个新类,名为dadad,如他在文章中提到的@kindall。虽然它们也无法精确排序,但它们会保留或记住向它们添加键和关联值的顺序,而不管是如何进行的,包括通过Update方法。这意味着您可以通过按所需顺序添加从输入字典到输出字典的所有内容来实现所需的功能

要做到这一点,您的代码在创建您称之为列表值键列表并对其排序的意义上是正确的。与使用内置ZipFunction相比,有一种更简单、更快的方法来创建该列表的初始未排序版本。下面是说明如何执行此操作的代码:

from collections import OrderedDict

adict = {1:1, 2:2, 5:1, 10:2, 44:3, 67:2} # input dictionary

# zip together and sort pairs by first item (value)
value_keys_list = sorted(zip(adict.values(), adict.keys()))

sorted_adict = OrderedDict() # value sorted output dictionary
for pair in value_keys_list:
    sorted_adict[pair[1]] = pair[0]

print sorted_adict
# OrderedDict([(1, 1), (5, 1), (2, 2), (10, 2), (67, 2), (44, 3)])
上述内容可以改写为相当优雅的一行:

sorted_adict = OrderedDict((pair[1], pair[0])
                   for pair in sorted(zip(adict.values(), adict.keys())))

您好-请编辑您的问题,选择问题的代码部分,然后点击“1010101”按钮,将您的代码格式化为代码。可能最简单的方法是在需要排序时使用键函数进行排序。sortedadict.iteritems,key=lambda x:x[1]唯一的问题是排序问题,它是一个列表,而不是一个字典。