如何按键对字典进行排序?

示例输入:

{2:3, 1:89, 4:5, 3:0}

期望的输出:

{1:89, 2:3, 3:0, 4:5}

当前回答

from operator import itemgetter
# if you would like to play with multiple dictionaries then here you go:
# Three dictionaries that are composed of first name and last name.
user = [
    {'fname': 'Mo', 'lname': 'Mahjoub'},
    {'fname': 'Abdo', 'lname': 'Al-hebashi'},
    {'fname': 'Ali', 'lname': 'Muhammad'}
]
#  This loop will sort by the first and the last names.
# notice that in a dictionary order doesn't matter. So it could put the first name first or the last name first. 
for k in sorted (user, key=itemgetter ('fname', 'lname')):
    print (k)

# This one will sort by the first name only.
for x in sorted (user, key=itemgetter ('fname')):
    print (x)

其他回答

我的建议是这样的,因为它允许你在添加项和将来可能需要添加项时对字典排序或保持字典排序:

从头开始构建词典。有第二个数据结构,一个包含键列表的列表。bisect包有一个insort函数,允许插入到一个排序的列表中,或者在完全填充字典后对列表进行排序。现在,当您迭代字典时,您将迭代列表以按顺序访问每个键,而不用担心字典结构的表示(它不是为排序而设计的)。

有一个简单的方法:

d = {2:3, 1:89, 4:5, 3:0}

s = {k : d[k] for k in sorted(d)}

s
Out[1]: {1: 89, 2: 3, 3: 0, 4: 5} 

您可以根据您的问题按键对当前字典进行排序,从而创建一个新字典。

这是你的字典

d = {2:3, 1:89, 4:5, 3:0}

通过使用lambda函数对这个d排序,创建一个新字典d1

d1 = dict(sorted(d.items(), key = lambda x:x[0]))

D1应为{1:89,2:3,3:0,4:5},根据d中的键进行排序。

dictionary = {1:[2],2:[],5:[4,5],4:[5],3:[1]}

temp=sorted(dictionary)
sorted_dict = dict([(k,dictionary[k]) for i,k in enumerate(temp)])

sorted_dict:
         {1: [2], 2: [], 3: [1], 4: [5], 5: [4, 5]}

简单:

d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items())

for k,v in sd:
    print k, v

输出:

1 89
2 3
3 0
4 5