需要帮助python中的sort函数

leb*_*lev 2 python sorting dictionary key

我的字典的内容是这样的: -

>>> dict
{'6279': '45', '15752': '47', '5231': '30', '475': '40'}
Run Code Online (Sandbox Code Playgroud)

我尝试在键上使用sort函数.我注意到sort函数对于密钥不起作用 - 15752.请在下面找到: -

>>> [k for k in sorted(dict.keys())]
['15752', '475', '5231', '6279']
Run Code Online (Sandbox Code Playgroud)

有人能指出我解决这个问题的方法吗?

谢谢


我的预期产量是: -

['475', '5231', '6279', '15752']
Run Code Online (Sandbox Code Playgroud)

Dan*_* D. 10

啊你想要按数值而不是字符串排序,所以你应该int(s)在之前或只是使用时将字符串转换为数字sorted(dict.keys(), key=int)