Reputation: 323
I have python ordinary dictionary. In this, insertion order is not preserved. I need to keep elements in insertion order. I know that OrderedDict
can do this job. but, my problem is i need to get an ordered dictionary from an already existing ordinary dictionary. This dictionary cannot be changed. Following is my ordinary dictionary:
d = {'tag': {'a': 1, 'c': {'k': 8}, 'b': 7, 'n': 6}}
Is there any way in python to keep order of elements in an already existing dictionary? Any help is appreciated. Using python 2.7
Upvotes: 2
Views: 2517
Reputation: 3467
Okay lets get it straight.. theoretically it's not possible.
But just for laughs..
Since you yourself are looking at the shell output and figuring out the order (I'm assuming so since how else would you yourself know the order?) So here we go..
import re
d = {'tag': {'a': 1, 'b': 7, 'c': {'k': 8}, 'n': 6}}
tags = d['tag']
sorted_keys = set(re.findall(r"'(\w)':", str(tags))).intersection(tags.keys())
print sorted_keys # You can form your OrderedDict
Upvotes: 0
Reputation: 133754
Short Answer: This is not possible, once you have created the dictionary it has no order.
Items are stored according to their hash and not their insertion order, you need to have the OrderedDict
created at the start so it can record insertion order as items are inserted.
Upvotes: 8