是python dict str()函数可靠地排序键? [英] is the python dict str() function reliably sorting keys?
问题描述
在python中,dict {1:1,2:2,3:3}
和 {3:3,2:2 ,1:1}
生成{1:1,2:2,3:3}
当str()'d? p>
我可以依靠这个排序,还是至少基于这样一个事实,即在使用str()函数时,包含相同键/值的对象将生成相同的字符串? p>
您可以依赖这两个属性。转换为字符串的字典顺序也取决于键/值对的插入顺序。
有一点Python源代码知识强大字典 from PyCon 2010),或者一些尝试和错误,你可以很容易地找到例子:
>> > {1:1,9:9}
{1:1,9:9}
>>> {9:9,1:1}
{9:9,1:1}
in python, both the dict {1:1,2:2,3:3}
and {3:3,2:2,1:1}
produces "{1:1,2:2,3:3}"
when str()'d?
Can I rely on this sorting, or at least on the fact that dicts containing the same key/valuepairs will generate the same string when put through the str() function?
You can rely on neither of these two properties. The order of a dictionary when converted to a string depends also on the insertion order of the key/value pairs.
With a bit of knowledge of the Python source code (watch The Mighty Dictionary from PyCon 2010), or a bit of trial and error, you can easily find counter examples:
>>> {1: 1, 9: 9}
{1: 1, 9: 9}
>>> {9: 9, 1: 1}
{9: 9, 1: 1}
这篇关于是python dict str()函数可靠地排序键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!