简体   繁体   English

dict.items() 返回的列表中元素的顺序是否始终相同?

[英]Is order of elements in list returned by dict.items() same all the time?

I am using a recursive code as below:我正在使用如下递归代码:

    def dfs(self, hash_map):
        ans = 1
        for key,value in hash_map.items():
            if value > 0:
                hash_map[key] = hash_map[key] - 1
                ans = ans + self.dfs(hash_map)
                hash_map[key] = value 
        return ans

So will the list returned by items() method in the dictionary retain the order?那么字典中items()方法返回的列表会保留顺序吗?

Not necessarily, it depends on what version of Python you're using.不一定,这取决于您使用的是什么版本的 Python。 check out OrderedDict查看OrderedDict

From the docs:从文档:

Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations.有序词典就像普通词典一样,但具有一些与排序操作相关的额外功能。 They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).现在它们变得不那么重要了,因为内置的字典 class 获得了记住插入顺序的能力(这种新行为在 Python 3.7 中得到保证)。

If you were relying on the order of keys in a Python dictionary or set, then don't.如果您依赖 Python 字典或集合中的键顺序,那么不要。 Python uses a hash table to implement these types and their order depends on the insertion and deletion history as well as the random hash seed. Python 使用 hash 表来实现这些类型,它们的顺序取决于插入和删除历史以及随机 hash 种子。

More details with about the fact can be found here: hash function in Python 3.3 returns different results between sessions可以在此处找到有关该事实的更多详细信息: hash function in Python 3.3 在会话之间返回不同的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM