Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 309
Eka Avatar asked Jul 15 '17 05:07

Eka


People also ask

How do I add an OrderedDict in Python?

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.

How do I create an empty OrderedDict in Python?

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.

What is OrderedDict in Python?

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.

Can you create an ordered dictionary in Python?

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.


1 Answers

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.

like image 139
Mark Avatar answered Sep 30 '22 11:09

Mark