How to create an OrderedDict in Python?

You need to pass it a sequence of items or insert items in order – that’s how it knows the order. Try something like this:

from collections import OrderedDict

domain = OrderedDict([('de', 'Germany'),
                      ('sk', 'Slovakia'),
                      ('hu', 'Hungary'),
                      ('us', 'United States'),
                      ('no', 'Norway')])

The array has an order, so the OrderedDict will know the order you intend.

Leave a Comment