简体   繁体   中英

How to maintain the order of a nested dictionary in python (not plain, but nested)?

I just copied a dictionary generated from another program to python program(hardcoded in python code).

a = {'b':{'d':3, 'c':4}, 'a':2}

but while reading the dictionary, the order is getting changed which is creating problem.

If I use OrderedDict also, only the top level order is getting saved but not of the inner dictionary.

I need the order as I am generating a tree based on the dictionary data, so that when I read back from that tree, I will get the same order. I am using python 2 version.

Thanks. Is this the drawback from python?

Edit: I am using this single line statement:

a = OrderedDict({'b':{'d':3, 'c':4}, 'a':2})

I just gave the simple dictionary as example but my actual dictionary is very big, so I cannot manually add OrderedDict to all inner dictionaries to make it ordered. Looking for solution in python 2, if not possible, please provide in python 3

Your inner dictionary should also be an OrderedDict.

You could alternatively use an associative list (a list of key-value pairs). I think this is closer to what you're trying to do: respecting the exact order or what you read.

Another alternative is to maintain a list (for the order) and a dict to access elements. This must be done at every level.

Dictionaries are not ordered in Python 2.x

So any solution which reads in your data as a regular dictionary will be useless to you. You need to focus on this aspect of your workflow first, for which you have provided no information or code.

Use lists of tuples with OrderedDict

This is the incorrect way to initialise an OrderedDict :

a = OrderedDict({'b': {'d':3, 'c':4}, 'a':2})

This fails specifically because the dictionary you feed is unordered in Python 2.x. In addition, you haven't attempted to make the inner dictionary an OrderedDict .

You need, instead, to feed lists of tuples , which are ordered, to both the outer OrderedDict and inner OrderedDict :

from collections import OrderedDict

a = OrderedDict([('b', OrderedDict([('b', 3), ('c', 4)])), ('a', 2)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM