如何按键对字典进行排序?
示例输入:
{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 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/
其他回答
有一个简单的方法:
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}
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)
我的建议是这样的,因为它允许你在添加项和将来可能需要添加项时对字典排序或保持字典排序:
从头开始构建词典。有第二个数据结构,一个包含键列表的列表。bisect包有一个insort函数,允许插入到一个排序的列表中,或者在完全填充字典后对列表进行排序。现在,当您迭代字典时,您将迭代列表以按顺序访问每个键,而不用担心字典结构的表示(它不是为排序而设计的)。
有一种简单的方法来整理字典。
根据你的问题,
解决方案是:
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)]
因此,通过将其更改为键、值和项,您可以像您想要的那样打印。希望这能有所帮助!
来自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)])