如何按键对字典进行排序?
示例输入:
{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}
当前回答
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)
其他回答
我发现对字典进行排序的一个简单方法是,根据要排序的字典的排序键:值项创建一个新字典。 如果你想对dict ={}排序,使用相关的方法检索它的所有项,使用sorted()函数对它们排序,然后创建新字典。
下面是使用字典理解的代码:
sorted_dict = {k:v for k,v in sorted(dict.items())}
来自Python的集合库文档:
>>> from collections import OrderedDict
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
>>> # dictionary sorted by key -- OrderedDict(sorted(d.items()) also works
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
2.7中两个方法的时间比较显示它们实际上是相同的:
>>> setup_string = "a = sorted(dict({2:3, 1:89, 4:5, 3:0}).items())"
>>> timeit.timeit(stmt="[(k, val) for k, val in a]", setup=setup_string, number=10000)
0.003599141953657181
>>> setup_string = "from collections import OrderedDict\n"
>>> setup_string += "a = OrderedDict({1:89, 2:3, 3:0, 4:5})\n"
>>> setup_string += "b = a.items()"
>>> timeit.timeit(stmt="[(k, val) for k, val in b]", setup=setup_string, number=10000)
0.003581275490432745
伙计们,你们把事情搞复杂了……非常简单
from pprint import pprint
Dict={'B':1,'A':2,'C':3}
pprint(Dict)
输出结果为:
{'A':2,'B':1,'C':3}
有一种简单的方法来整理字典。
根据你的问题,
解决方案是:
c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y
(其中c是你的字典名。)
这个程序给出如下输出:
[(1, 89), (2, 3), (3, 0), (4, 5)]
如你所愿。
另一个例子是:
d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x
给出输出:['Albert', 'Bill', 'John', 'Lucy', 'Peter']
y=sorted(d.values())
print y
给出输出:[18,24,32,36,41]
z=sorted(d.items())
print z
给出输出:
[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]
因此,通过将其更改为键、值和项,您可以像您想要的那样打印。希望这能有所帮助!