如果没有修改,是否可以保留迭代顺序? [英] Do dicts preserve iteration order if they are not modified?

查看:122
本文介绍了如果没有修改,是否可以保留迭代顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Python中有一个字典,并且迭代一次,然后再次,迭代顺序保证被保留,因为我没有插入,删除或更新字典中的任何项目? (但我可能已经做了查找)。

解决方案

这是什么 dict.items() 文档说:


dict.items()返回一个字典的(key,value)对列表的副本。



如果调用items(),keys(),values(),iteritems(),iterkeys()和itervalues()),而不会对字典进行任何修改,则列表将直接对应。 / p>

我认为如果您所做的是迭代,项目排序不会改变是合理的。


If I have a dictionary in Python, and I iterate through it once, and then again later, is the iteration order guaranteed to be preserved given that I didn't insert, delete, or update any items in the dictionary? (But I might have done look-ups).

解决方案

Here is what dict.items() documentation says:

dict.items() return a copy of the dictionary’s list of (key, value) pairs.

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

I think it's reasonable to assume that item ordering won't change if all you do is iteration.

这篇关于如果没有修改,是否可以保留迭代顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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