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

示例输入:

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

期望的输出:

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

当前回答

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]}

其他回答

我认为最简单的事情是按键对字典进行排序,并将排序的键:值对保存在一个新的字典中。

dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2} 
dict2 = {}                  # create an empty dict to store the sorted values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be neccessary
        dict2[key] = dict1[key]

更清楚地说:

dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2} 
dict2 = {}                  # create an empty dict to store the sorted     values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be  neccessary
        value = dict1[key]
        dict2[key] = value

如果你知道你所有的键都是相同的类型,或者有支持'< '(小于,python的__lt__)的类型,那么你可以使用dict(sorted(your_dict.items(), key=lambda _: _[0]))一个容易理解的一行程序

这里已经有很多答案展示了对Python字典进行排序的流行方法。我想我应该为那些从谷歌来到这里寻找非标准想法的人添加一些不太明显的方法。

样本字典:d = {2: ' c ', 1: ' b ', 0: ' a ', 3: ' d '}

字典理解

# Converts to list, sorts, re-converts to dict
{k: v for k, v in sorted(list(d.items()))}

使用λ

排序并不总是按照严格的升序或降序进行。对于更多的条件排序,使用上述方法结合lamdas:

{k: v for k, v in sorted(d.items(), key=lambda v: ord(v[1]))}

更多的例子

这个帖子已经有足够多的好例子了。有关更多示例,以及边缘情况和奇怪情况,请参阅这篇关于Python中字典排序的文章。

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

这是你的字典

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中的键进行排序。

此函数将根据键对任何字典进行递归排序。也就是说,如果字典中的任何值也是一个字典,它也将根据它的键进行排序。如果您运行在CPython 3.6或更高版本上,则可以简单地更改为使用dict而不是OrderedDict。

from collections import OrderedDict

def sort_dict(d):
    items = [[k, v] for k, v in sorted(d.items(), key=lambda x: x[0])]
    for item in items:
        if isinstance(item[1], dict):
            item[1] = sort_dict(item[1])
    return OrderedDict(items)
    #return dict(items)