为相等的值排序字典键

时间:2017-12-24 11:28:32

标签: python python-3.x sorting dictionary

我有一个使用计数器形成的字典:

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}

1 个答案:

答案 0 :(得分:2)

以下是您为获得预期结果而需要做的高级细分。

  1. 在构建Counter时,只需传递all_years即可。

  2. 默认情况下,未对python< 3.6中的词典进行排序,因此您需要使用OrderedDict

  3. 排序时,请确保先按多个谓词 - 排序,然后按排序。

  4. 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])))
    

    字典按照传递给它的顺序构建。