collections.OrderedDict

suggest change

The order of keys in Python dictionaries is arbitrary: they are not governed by the order in which you add them.

For example:

>>> d = {'foo': 5, 'bar': 6}
>>> print(d)
{'foo': 5, 'bar': 6}
>>> d['baz'] = 7
>>> print(a)
{'baz': 7, 'foo': 5, 'bar': 6}
>>> d['foobar'] = 8
>>> print(a)
{'baz': 7, 'foo': 5, 'bar': 6, 'foobar': 8}

(The arbitrary ordering implied above means that you may get different results with the above code to that shown here.) The order in which the keys appear is the order which they would be iterated over, e.g. using a `for` loop. The collections.OrderedDict class provides dictionary objects that retain the order of keys. OrderedDict can be created as shown below with a series of ordered items (here, a list of tuple key-value pairs):

from collections import OrderedDict
d = OrderedDict([(foo, 5), (bar, 6)])
print(d)
> OrderedDict([(foo, 5), (bar, 6)])
d[baz] = 7
print(d)
> OrderedDict([(foo, 5), (bar, 6), (baz, 7)])
d[foobar] = 8
print(d)
> OrderedDict([(foo, 5), (bar, 6), (baz, 7), (foobar, 8)])

Or we can create an empty `OrderedDict` and then add items:

o = OrderedDict()
o[key1] = value1
o[key2] = value2
print(o)
> OrderedDict([(key1, value1), (key2, value2)])

Iterating through an OrderedDict allows key access in the order they were added.

What happens if we assign a new value to an existing key?

d[foo] = 4
print(d)
> OrderedDict([(foo, 4), (bar, 6), (baz, 7), (foobar, 8)])

The key retains its original place in the OrderedDict.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Collections module:
* collections.OrderedDict

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
32 Collections module
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve