是python dict str()函数可靠地排序键? [英] is the python dict str() function reliably sorting keys?

查看:120
本文介绍了是python dict str()函数可靠地排序键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆