按一些值和键对字典词典进行排序

时间:2019-04-16 13:07:51

标签: python dictionary

我正在尝试根据字典中“点”和“赢”这两个值,然后按键对字典进行排序。我可以像下面这样基于“点数”和“胜利”对它进行排序,但是我也该如何按名称对其进行排序?

my_dic = {
    'Iran': {'Points': 4, 'win': 1, 'lose': 1, 'drawes': 1, 'diffrence': 0}, 
    'Spain': {'Points': 5, 'win': 1, 'lose': 0, 'drawes': 2, 'diffrence': 2}, 
    'Portugal': {'Points': 4, 'win': 1, 'lose': 1, 'drawes': 1, 'diffrence': 0}, 
    'Morocco': {'Points': 3, 'win': 1, 'lose': 2, 'drawes': 0, 'diffrence': -2}
}

result = collections.OrderedDict(sorted(my_dic.items(),key = lambda x: (x[1]['Points'],x[1]['win']), reverse = True) )
  

输出:

OrderedDict([
    ('Spain', {'Points': 5, 'win': 1, 'lose': 0, 'drawes': 2, 'diffrence': 2}), 
    ('Iran', {'Points': 4, 'win': 1, 'lose': 1, 'drawes': 1, 'diffrence': 0}), 
    ('Portugal', {'Points': 4, 'win': 1, 'lose': 1, 'drawes': 1, 'diffrence': 0}), 
    ('Morocco', {'Points': 3, 'win': 1, 'lose': 2, 'drawes': 0, 'diffrence': -2})
])

我的代码已经基于'Points'和'win'对dict进行排序。但是我希望当'Points'和'win'相等时,dict是根据键Iran, Spain, Portugal, Moroco排序的。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这可以做到:

sorted_keys = sorted(my_dic, key=lambda x: (my_dic[x]['Points'], my_dic[x]['win'], x),  
                     reverse=True)
print([(key, my_dic[key]) for key in sorted_keys])

Output: 

[('Spain', {'Points': 5, 'diffrence': 2, 'drawes': 2, 'lose': 0, 'win': 1}),
 ('Portugal', {'Points': 4, 'diffrence': 0, 'drawes': 1, 'lose': 1, 'win': 1}),
 ('Iran', {'Points': 4, 'diffrence': 0, 'drawes': 1, 'lose': 1, 'win': 1}),
 ('Morocco', {'Points': 3, 'diffrence': -2, 'drawes': 0, 'lose': 2, 'win': 1})]

答案 1 :(得分:0)

这是解决方案:

CS 1705

话虽如此,如果您正在对result = collections.OrderedDict(sorted(my_dic.items(),key = lambda x: (-x[1]['Points'], -x[1]['win'], x[0])) ) 进行排序...则可能不应该使用dict ... 考虑改用dict之类的东西。

namedtuple

输出:

from collections import namedtuple
my_dic = {
    'Iran': {'Points': 4, 'win': 1, 'lose': 1, 'drawes': 1, 'diffrence': 0}, 
    'Spain': {'Points': 5, 'win': 1, 'lose': 0, 'drawes': 2, 'diffrence': 2}, 
    'Portugal': {'Points': 4, 'win': 1, 'lose': 1, 'drawes': 1, 'diffrence': 0}, 
    'Morocco': {'Points': 3, 'win': 1, 'lose': 2, 'drawes': 0, 'diffrence': -2}
}
Country = namedtuple("Country", "name stats")
Stats = namedtuple("Stats", "points win lose drawes difference")
countries = []
for key, value in my_dic.items():
    temp_stat = Stats(value["Points"], value["win"], value["lose"], value["drawes"], value["diffrence"])
    countries.append(Country(key, temp_stat))


def sort_funct(x):
    # The order in which we want to sort by
    return (-x.stats.points, -x.stats.win, x.name)

countries.sort(key=sort_funct)

for country in countries:
    print_str = "{} has {} points and {} wins".format(country.name, country.stats.points, country.stats.win)
    print(print_str)
相关问题