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.
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. Actually, you can load an OrderedDict using json. load(). There is a second parameter which tells the load method to create an OrderedDict object to keep order the same.
OrderedDict is part of python collections module. We can create an empty OrderedDict and add items to it. If we create an OrderedDict by passing a dict argument, then the ordering may be lost because dict doesn't maintain the insertion order. If an item is overwritten in the OrderedDict, it's position is maintained.
Python's OrderedDict is a dict subclass that preserves the order in which key-value pairs, commonly known as items, are inserted into the dictionary. When you iterate over an OrderedDict object, items are traversed in the original order. If you update the value of an existing key, then the order remains unchanged.
We can create ordered dictionary using OrderedDict function in collections. Ordered dictionary preserves the insertion order. We can iterate through the dictionary items and see that the order is preserved.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With