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.
You can use
OrderedDict
but you have to take in consideration thatOrderedDict
will not work outside of your running code.This means that exporting the object to JSON will lose all the effects of
OrderedDict
.What you can do is create a metadata array in which you can store the keys
"de", sk", etc.
in an ordered fashion. By browsing the array in order you can refer to the dictionary properly, and the order in array will survive any export in JSON, YAML, etc.Current JSON:
New object
countries
:Code that will print the long names in order:
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:
The array has an order, so the OrderedDict will know the order you intend.
In the
OrderedDict
case, you are creating an intermediate, regular (and hence unordered) dictionary before it gets passed to the constructor. In order to keep the order, you will either have to pass something with order to the constructor (e.g. a list of tuples) or add the keys one-by-one in the order you want (perhaps in a loop).Late answer, but here's a
python 3.6+
oneliner tosort
dictionaries bykey
without using imports:Output:
Python Demo