Do dicts preserve iteration order if they are not

2019-04-03 10:10发布

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).

7条回答
We Are One
2楼-- · 2019-04-03 10:37

A Python dictionary has no concept of order. So you can't depend on a specific order while iterating.

This is deliberate: since it's a hashmap it's unavoidable if you want 'fast lookups'!

查看更多
forever°为你锁心
3楼-- · 2019-04-03 10:39

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.

查看更多
叛逆
4楼-- · 2019-04-03 10:46

As Christophe said, a dictionary is used to organise key/value pairs because of the fast access time it provides. If you application needs a fixed index, you should look at the other data structures that provide a specific/known order.

Having said that, it should be safe to assume that the order doesn't change unless items are added (there wouldn't be any point to do this expensive operation of reshuffling stuff) etc but, again, don't rely on it.

查看更多
贪生不怕死
5楼-- · 2019-04-03 10:47

The standard Python dict like most implementations does not preserve ordering as the items are usually accessed using the key.

However predictable iteration is sometime useful and in Python 3.1 the collections module contains an OrderedDict that is order preserving with minimal performance overhead.

查看更多
冷血范
6楼-- · 2019-04-03 10:48

It might be preserved in some implementations, but don't count on it, as it is not a part of the Dict spec.

查看更多
SAY GOODBYE
7楼-- · 2019-04-03 10:51

collections.OrderedDict will be available in Python 2.7 in addition to Python 3.1.

For Python versions earlier than 2.7, there's collective.ordereddict on PyPI, and Django has its own SortedDict implementation.

查看更多
登录 后发表回答