Creating an ordered dictionary

suggest change

You can create an ordered dictionary which will follow a determined order when iterating over the keys in the dictionary. A built-in dict also keeps insertion order since Python 3.7. OrderedDict still treats order as part of equality and provides move_to_end().

Use OrderedDict from the collections module. This will always return the dictionary elements in the original insertion order when iterated over.

from collections import OrderedDict

d = OrderedDict()
d['first'] = 1
d['second'] = 2
d['third'] = 3
d['last'] = 4

# Outputs "first 1", "second 2", "third 3", "last 4"
for key in d:
    print(key, d[key])

Feedback about page:

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



Table Of Contents