Python Language Dictionary Creating an ordered dictionary

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

You can create an ordered dictionary which will follow a determined order when iterating over the keys in the dictionary.

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


Got any Python Language Question?