如何按键对字典进行排序?
示例输入:
{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}
当前回答
注意:对于Python 3.7+,请参见此答案
标准Python字典是无序的(直到Python 3.7)。即使对(键,值)对进行了排序,也不能将它们存储在字典中以保持排序。
最简单的方法是使用OrderedDict,它会记住元素被插入的顺序:
In [1]: import collections
In [2]: d = {2:3, 1:89, 4:5, 3:0}
In [3]: od = collections.OrderedDict(sorted(d.items()))
In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
不要在意od是如何打印出来的;它会像预期的那样工作:
In [11]: od[1]
Out[11]: 89
In [12]: od[3]
Out[12]: 0
In [13]: for k, v in od.iteritems(): print k, v
....:
1 89
2 3
3 0
4 5
Python 3
对于Python 3用户,需要使用.items()而不是.iteritems():
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
其他回答
来自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)])
我想出了单行字典排序。
>> a = {2:3, 1:89, 4:5, 3:0}
>> c = {i:a[i] for i in sorted(a.keys())}
>> print(c)
{1: 89, 2: 3, 3: 0, 4: 5}
[Finished in 0.4s]
希望这对你有所帮助。
在Python 3中。
>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
print (key, D1[key])
给了
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)
注意:对于Python 3.7+,请参见此答案
标准Python字典是无序的(直到Python 3.7)。即使对(键,值)对进行了排序,也不能将它们存储在字典中以保持排序。
最简单的方法是使用OrderedDict,它会记住元素被插入的顺序:
In [1]: import collections
In [2]: d = {2:3, 1:89, 4:5, 3:0}
In [3]: od = collections.OrderedDict(sorted(d.items()))
In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
不要在意od是如何打印出来的;它会像预期的那样工作:
In [11]: od[1]
Out[11]: 89
In [12]: od[3]
Out[12]: 0
In [13]: for k, v in od.iteritems(): print k, v
....:
1 89
2 3
3 0
4 5
Python 3
对于Python 3用户,需要使用.items()而不是.iteritems():
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5