我有这本字典:
a = {'Atlanta': 4, 'Bronx': 4, 'San Diego': 30}
我目前知道如何按值从大到小对其进行排序:
s = sorted(a.items(), key = lambda t:t[1], reverse=True)
s = [('San Diego', 30), ('Atlanta', 4), ('Bronx', 4)]
我想做的是当两个键的值相同时,我想按字母倒序对它们进行排序。所以我想要的结果是:
s = [('San Diego', 30), ('Bronx', 4), ('Atlanta', 4)]
而不是我上面的。有没有方便的方法来做到这一点?
请您参考如下方法:
可以用元组对次要条件进行排序
s = dict(sorted(a.items(), key= lambda x: (x[1], x[0]), reverse = True))
# {'San Diego': 30, 'Bronx': 4, 'Atlanta': 4}
