如何按包含 dashes/hyphens 的值对字典进行排序?

How to sort a dictionary by values that contain dashes/hyphens?

我有一本描述球队记录的字典。我想按值对字典进行排序,这些值是数值中的输赢数字。 代码:

standings = {'Memphis': '23-12', 'Seattle': '10-25, 'Boston': '35-0', 'Dallas': '20-15'}

打印时的预期结果:

{'Boston': 35-0, 'Memphis': 23-12, 'Dallas': 20-15, 'Seattle': 10-25}

如何对字典进行排序,使记录按数字顺序从高到低排列? 感谢您的帮助。

这取决于您使用的 python 版本,与之前 python 3.6 一样,dict 项目是无序的,更准确地说,不能保证您的 dict 会保持任何顺序可以想象。 也就是说,如果您使用的是 3.6+

>>> dict(sorted(standings.items(), key=lambda x: tuple(map(int, x[1].split('-'))), reverse=True))
{'Boston': '35-0', 'Memphis': '23-12', 'Dallas': '20-15', 'Seattle': '10-25'}