我有一个使用计数器形成的字典:
c = collections.Counter()
for y in all_years: # iterator
c[y] += 1
d = dict(c.most_common())
print(d)
/ 所有年份都包含250年值列表 /
结果:{1995:9,1957:7,2003:7,2000:7,2001:6,1975:6,2014:6,2009:6,1994:5,1999:5,2010:5 ,2002:5,1997:5}
是否可以按年份对此字典中的相等值进行排序: 例如{1995:9,1957:7,2000:7,2003:7,1975:6,2001:6,2014:6 etc}
答案 0 :(得分:2)
以下是您为获得预期结果而需要做的高级细分。
在构建Counter
时,只需传递all_years
即可。
默认情况下,未对python< 3.6中的词典进行排序,因此您需要使用OrderedDict
。
排序时,请确保先按多个谓词 - 值排序,然后按键排序。
from collections import Counter, OrderedDict
c = Counter(all_years)
r = OrderedDict(sorted(d.items(), key=lambda x: (-x[1], x[0])))
OrderedDict([(1995, 9),
(1957, 7),
(2000, 7),
(2003, 7),
(1975, 6),
(2001, 6),
(2009, 6),
(2014, 6),
(1994, 5),
(1997, 5),
(1999, 5),
(2002, 5),
(2010, 5)])
感谢Stefan Pochmann的改进。
要解释一下key=lambda x: (-x[1], x[0])
的更多信息,这就是它的工作原理:
x[1]
是第一位的。您还希望按降序排序,因此否定它。由于x[1]
保证为计数,因此这适用于任何Counter
输出x[0]
。 在python 3.6中,只需将sorted
的结果传递给dict
构造函数 -
r = dict(sorted(d.items(), key=lambda x: (-x[1], x[0])))
字典按照传递给它的顺序构建。