How to create an OrderedDict in Python?

2024/11/19 3:44:48

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 OrderedDictdomain1 = { "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.

Answer

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 OrderedDictdomain = 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.

https://en.xdnf.cn/q/26488.html

Related Q&A

How to log error to file, and not fail on exception

I am downloading a file from the net, and it fails even though I am doing: for p in query:try:except IOError as e:print e;If there is an error, I want to log it, and then continue on with the next file…

Suggestions for Python debugging tools? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site …

How can you bundle all your python code into a single zip file?

It would be convenient when distributing applications to combine all of the eggs into a single zip file so that all you need to distribute is a single zip file and an executable (some custom binary tha…

Pass Variable On Import

Lets say you have some time-consuming work to do when a module/class is first imported. This functionality is dependent on a passed in variable. It only needs to be done when the module/class is load…

Write a file to a directory that doesnt exist [duplicate]

This question already has answers here:How do I create a directory, and any missing parent directories?(27 answers)Closed 9 months ago.This post was edited and submitted for review 8 months ago and fa…

How to convert a string to an image?

I started to learn python a week ago and want to write a small program that converts a email to a image (.png) so that it can be shared on forums without risking to get lots of spam mails. It seems lik…

Numpy list of 1D Arrays to 2D Array

I have a large list files that contain 2D numpy arrays pickled through numpy.save. I am trying to read the first column of each file and create a new 2D array.I currently read each column using numpy.…

What is metrics in Keras?

It is not yet clear for me what metrics are (as given in the code below). What exactly are they evaluating? Why do we need to define them in the model? Why we can have multiple metrics in one model?…

ObjectNotExecutableError when executing any SQL query using AsyncEngine

Im using async_engine. When I try to execute anything: async with self.async_engine.connect() as con:query = "SELECT id, name FROM item LIMIT 50;"result = await con.execute(f"{query}&quo…

Store the cache to a file functools.lru_cache in Python = 3.2

Im using @functools.lru_cache in Python 3.3. I would like to save the cache to a file, in order to restore it when the program will be restarted. How could I do?Edit 1 Possible solution: We need to pi…