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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…