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).
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
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'!
Here is what
dict.items()
documentation says:I think it's reasonable to assume that item ordering won't change if all you do is iteration.
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.
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.It might be preserved in some implementations, but don't count on it, as it is not a part of the Dict spec.
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.