0

Dose any one here know how to change the order of the order dictionary variables in python . I have tried to change the order of the key list but it didn't change the order of the dictionary .

For example i want to change the order of d
to ['e','a','b','c','d'] instead of ['a','b','c','d','e']

d = collections.OrderedDict()
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
kitkat
  • 9
  • 1
  • 2

3 Answers3

2

You need to create a new object of the same type as d. Here I use type(d) which is of course OrderedDict in this case

>>> import collections
>>> d = collections.OrderedDict()
>>> d['a'] = 'A'
>>> d['b'] = 'B'
>>> d['c'] = 'C'
>>> d['d'] = 'D'
>>> d['e'] = 'E'
>>> new_order = ['e','a','b','c','d'] 
>>> type(d)((k, d[k]) for k in new_order)
OrderedDict([('e', 'E'), ('a', 'A'), ('b', 'B'), ('c', 'C'), ('d', 'D')])
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
2

If you're using python3 you don't necessarily have to create a new dictionary.

You can use OrderedDict.move_to_end:

Move an existing key to either end of an ordered dictionary. The item is moved to the right end if last is true (the default) or to the beginning if last is false. Raises KeyError if the key does not exist <... provides example>

Example (moving e to start of dictionary to achieve your output):

>>> d = OrderedDict()
>>> for c in 'ABCDE':
...     d[c.lower()] = c
...
>>> d
OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C'), ('d', 'D'), ('e', 'E')])
>>> d.move_to_end('e',last=False) # last=False moves to beginning
>>> d
OrderedDict([('e', 'E'), ('a', 'A'), ('b', 'B'), ('c', 'C'), ('d', 'D')])
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
1

You will have to create another OrderedDict

new_keys = ['e','a','b','c','d']
new_dict = collections.OrderedDict()
for i in new_keys:
    new_dict[i] = d[i]
Kidus
  • 1,785
  • 2
  • 20
  • 36