我有一个字典:{'a':10,'b':20,'c':5,'d':5,'e':5},想要获取它的内容。
b 20
a 10
c 5
d 5
e 5
按值排序,如果有相等的值,则必须按字典序排序。
注意:使用Python 2。
-
反转 int 值:d = {'a':10,'b':20,'c':5,'d':5,'e':5}
for k,v in sorted(d.items(),key=lambda x:(-x[1],x[0])):
print("{} {}".format(k,v))
输出:
b 20
a 10
c 5
d 5
e 5
collections.OrderedDict
的内容)。>>> d = {'a':10,'b':20,'c':5,'d':5,'e':5}
>>> list(sorted(d.items(), key = lambda i : (i[1],i[0]), reverse = True))
[('b', 20), ('a', 10), ('e', 5), ('d', 5), ('c', 5)]
>>> for x in sorted(d.items(), key=lambda x: (-x[1], x[0])):
print x[0], x[1]
b 20
a 10
c 5
d 5
e 5
from collections import OrderedDict
print OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('a', 10), ('b', 20), ('c', 5), ('d', 5), ('e', 5)])
ord
。 - jamylak