How to create an OrderedDict in Python?

Viewed 38123

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.

4 Answers

Late answer, but here's a python 3.6+ oneliner to sort dictionaries by key without using imports:

d = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  }
d_sorted = {k: v for k, v in sorted(d.items(), key=lambda x: x[1])}
print(d_sorted)

Output:

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

Python Demo

Related