pythondictionaryordereddict

How to create an OrderedDict in Python?


I tried to maintain the order of a Python dictionary, since native dict doesn't have any order to it. Many answers in SE suggested using OrderedDict.

from collections import OrderedDict

domain1 = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  }

domain2 = OrderedDict({ "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  })

print domain1
print " "    
for key,value in domain1.iteritems():
    print (key,value)

print " "

print domain2
print ""
for key,value in domain2.iteritems():
    print (key,value)

After iteration, I need the dictionary to maintain its original order and print the key and values as original:

{
    "de": "Germany",
    "sk": "Slovakia",
    "hu": "Hungary",
    "us": "United States",
    "no": "Norway"
}

Either way I used doesn't preserve this order, though.


Solution

  • 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.