如何按键对字典进行排序?
示例输入:
{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}
其他回答
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键排序顺序的列表,然后遍历dict。例如
a1 = {'a':1, 'b':13, 'd':4, 'c':2, 'e':30}
a1_sorted_keys = sorted(a1, key=a1.get, reverse=True)
for r in a1_sorted_keys:
print r, a1[r]
以下是输出(按顺序排列)
e 30
b 13
d 4
c 2
a 1
有一个简单的方法:
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}
在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
字典本身并没有这样的排序条目,如果你想按某种顺序打印它们,这里有一些例子:
在Python 2.4及以上版本中:
mydict = {'carl':40,
'alan':2,
'bob':1,
'danny':3}
for key in sorted(mydict):
print "%s: %s" % (key, mydict[key])
给:
alan: 2
bob: 1
carl: 40
danny: 3
(Python低于2.4:)
keylist = mydict.keys()
keylist.sort()
for key in keylist:
print "%s: %s" % (key, mydict[key])
来源:http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/