是python dict str()函数可靠地排序键?

big*_*ind 6 python string dictionary

在python中,dict {1:1,2:2,3:3}和str()时{3:3,2:2,1:1}生成"{1:1,2:2,3:3}"

我可以依赖这种排序,或者至少是因为当通过str()函数时,包含相同键/值对的dicts将生成相同的字符串这一事实?

Sve*_*ach 6

您可以依赖这两个属性.转换为字符串时字典的顺序还取决于键/值对的插入顺序.

通过对Python源代码的一些了解(观看PyCon 2010中的The Mighty Dictionary)或者一些试验和错误,您可以轻松找到反例:

>>> {1: 1, 9: 9}
{1: 1, 9: 9}
>>> {9: 9, 1: 1}
{9: 9, 1: 1}
Run Code Online (Sandbox Code Playgroud)