如何按键对字典进行排序?
示例输入:
{2:3, 1:89, 4:5, 3:0}
期望的输出:
{1:89, 2:3, 3:0, 4:5}
如何按键对字典进行排序?
示例输入:
{2:3, 1:89, 4:5, 3:0}
期望的输出:
{1:89, 2:3, 3:0, 4:5}
当前回答
对于CPython/PyPy 3.6,以及任何Python 3.7或更高版本,这很容易做到:
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}
其他回答
如果你知道你所有的键都是相同的类型,或者有支持'< '(小于,python的__lt__)的类型,那么你可以使用dict(sorted(your_dict.items(), key=lambda _: _[0]))一个容易理解的一行程序
此函数将根据键对任何字典进行递归排序。也就是说,如果字典中的任何值也是一个字典,它也将根据它的键进行排序。如果您运行在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)
我发现对字典进行排序的一个简单方法是,根据要排序的字典的排序键:值项创建一个新字典。 如果你想对dict ={}排序,使用相关的方法检索它的所有项,使用sorted()函数对它们排序,然后创建新字典。
下面是使用字典理解的代码:
sorted_dict = {k:v for k,v in sorted(dict.items())}
简单:
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
我认为最简单的事情是按键对字典进行排序,并将排序的键:值对保存在一个新的字典中。
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