我想根据分数对这个字典中的团队进行排序,并且我已经遵循了这篇post中的建议 我编写的排序代码无法按我想要的方式工作,
这是我的字典:
{
'Spain': {
'wins': 3,
'loses': 0,
'draws': 0,
'goal difference': 4,
'points': 9
},
'Iran': {
'wins': 0,
'loses': 3,
'draws': 0,
'goal difference': -6,
'points': 0
},
'Portugal': {
'wins': 2,
'loses': 1,
'draws': 0,
'goal difference': 4,
'points': 6
},
'Morocco': {
'wins': 1,
'loses': 2,
'draws': 0,
'goal difference': -2,
'points': 3
}
}
以及我用于排序的代码:
sorted_dict = OrderedDict(sorted(B_group.items(),key= lambda x: x[1]["points"] ,reverse=True))
这是我得到的结果:
Spain wins:3 , loses:0 , draws:0 , goal difference:4 , points:9
Iran wins:0 , loses:3 , draws:0 , goal difference:-6 , points:0
Portugal wins:2 , loses:1 , draws:0 , goal difference:4 , points:6
Morocco wins:1 , loses:2 , draws:0 , goal difference:-2 , points:3
我希望将积分最高的球队放在第一位,例如西班牙、葡萄牙、摩洛哥、伊朗在此列表中, 我写的排序代码有问题吗?
您不再需要使用
OrderedDict
。 dict
目前正在维护插入顺序。
试试这个:
d = {
"Spain": {"wins": 3, "loses": 0, "draws": 0, "goal difference": 4, "points": 9},
"Iran": {"wins": 0, "loses": 3, "draws": 0, "goal difference": -6, "points": 0},
"Portugal": {"wins": 2, "loses": 1, "draws": 0, "goal difference": 4, "points": 6},
"Morocco": {"wins": 1, "loses": 2, "draws": 0, "goal difference": -2, "points": 3},
}
sorted_d = dict(sorted(d.items(), key=lambda x: x[1]["points"], reverse=True))
print(sorted_d)
输出:
{'Spain': {'wins': 3, 'loses': 0, 'draws': 0, 'goal difference': 4, 'points': 9}, 'Portugal': {'wins': 2, 'loses': 1, 'draws': 0, 'goal difference': 4, 'points': 6}, 'Morocco': {'wins': 1, 'loses': 2, 'draws': 0, 'goal difference': -2, 'points': 3}, 'Iran': {'wins': 0, 'loses': 3, 'draws': 0, 'goal difference': -6, 'points': 0}}