Python中关于dict和set的输出差异性问题应该如何理解?

本人Python初学者,在python3.6练习代码发现,dict输出按照键值是有序的,而set集合输出是无序的,换句话说就是每次执行dict和set的输出,dict的都一样,但是set的内容不变而顺序会有变化。为什么会有这样的差异呢?
我查了一下是字典和集合的背后依托于散列表,散列表的工作原理我就不多说了。我自己猜测是Python在内部对于dict的输出是做了一些额外的处理所以导致它和set在输出上的差异,这么理解对吗?希望有明白原理的大神帮助我解答一下,感激不尽!

阅读 2.8k
3 个回答

python 3.6 的dict 是键是按顺序存放的,具体可以看 python 官方文档
New dict implementation

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).

但是不应该依赖 dict 键有序,因为以后的版本可能会变化,可是使用 ordereddict 明确指定键有序

dict是字典,set是集合,集合很重要的特性,无序性,唯一性,确定性(就是确定某个元素是不是在该集合中)。
所以set输出是无序的是没有问题的。
至于dict与set的输出差异,不会做出额外处理。

你之前学过其他语言吗?dictset都是通过hash实现的,所以原理上来说都是无序的。

但是python3.6之后,Python的dict的是按key值存入的时间排序的,没看过源码,但我猜是额外维护了一个key的链表。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题