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

2024-06-16 10:40:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着按两个值对字典进行排序,“Points”和“win”,然后按键。我可以像贝娄一样根据“积分”和“胜利”来排序,但是我怎么也可以根据名字来排序呢?你知道吗

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) )

Output:

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进行了排序。但是我希望dict是基于键来排序的,Iran, Spain, Portugal, Moroco,当'Points'和'win'相等时。你知道吗

感谢您的帮助。你知道吗


Tags: 字典排序mywindictpointsordereddictiran
2条回答

这样做可以:

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})]

以下是解决方案:

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)

输出:

Spain has 5 points and 1 wins
Iran has 4 points and 1 wins
Portugal has 4 points and 1 wins
Morocco has 3 points and 1 wins

相关问题 更多 >