Search code examples
pythonjsonstringdictionaryordereddictionary

Convert OrderedDict to normal dict preserving order?


How do I convert an OrderedDict to a normal dictionary while preserving the same order?

The reason I am asking this is because is when I fetch my data from an API, I get a JSON string, in which I use json.loads(str) to return a dictionary. This dictionary that is returned from json.loads(...) is just out of order and is randomly ordered. Also, I've read that OrderedDict is slow to work with so I want to use regular dict in same order as original JSON string.

Slightly off-topic: Is there anyway to convert a JSON string to a dict using json.loads(...) while maintaining the same order without using collections.OrderedDict?


Solution

  • Update: As of Python 3.6, builtin dicts behave like OrderedDict. That is, they preserve insertion order.


    When you convert an OrderedDict to a normal dict, you can't guarantee the ordering will be the preserved, because dicts are unordered. Which is why OrderedDict exists in the first place.

    It seems like you're trying to have your cake and eat it too, here. If you want the order of the JSON string preserved, use the answer from the question I linked to in the comments to load your json string directly into an OrderedDict. But you have to deal with whatever performance penalty that carries (I don't know offhand what that penalty is. It may even be neglible for you use-case.). If you want the best possible performance, just use dict. But it's going to be unordered.