我试着按两个值对字典进行排序,“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'相等时。你知道吗
感谢您的帮助。你知道吗
这样做可以:
以下是解决方案:
也就是说,如果你正在排序一个
dict
。。。您可能不应该使用dict
。。。 考虑使用类似于namedtuple
的东西。你知道吗输出:
相关问题 更多 >
编程相关推荐