Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the order of keys in a Python 3.5 dictionary, using another list as a reference for keys?

I'm trying to change the order of 'keys' in a dictionary, with no success. This is my initial dictionary:

Not_Ordered={
  'item':'book',
  'pages':200, 
  'weight':1.0, 
  'price':25, 
  'city':'London'
}

Is there a chance for me to change the order according to a key-order list, like this:

key_order=['city', 'pages', 'item', 'weight', 'price']

note:

  • I'm using Python 3.5.2.
  • I'm not looking for sorting the keys.
  • I'm aware that Python 3.6 follows the insertion.
  • Also, I'm aware of OrderedDict, but it gives me a list, but I'm looking for a dictionary as final result.
like image 675
Behrouz Beheshti Avatar asked Sep 02 '18 16:09

Behrouz Beheshti


2 Answers

Dicts are "officially" maintained in insertion order starting in 3.7. They were so ordered in 3.6, but it wasn't guaranteed before 3.7. Before 3.6, there is nothing you can do to affect the order in which keys appear.

But OrderedDict can be used instead. I don't understand your "but it gives me a list" objection - I can't see any sense in which that's actually true.

Your example:

>>> from collections import OrderedDict
>>> d = OrderedDict([('item', 'book'), ('pages', 200),
...                  ('weight', 1.0), ('price', 25),
...                  ('city', 'London')])
>>> d # keeps the insertion order
OrderedDict([('item', 'book'), ('pages', 200), ('weight', 1.0), ('price', 25), ('city', 'London')])
>>> key_order= ['city', 'pages', 'item', 'weight', 'price'] # the order you want
>>> for k in key_order: # a loop to force the order you want
...     d.move_to_end(k)
>>> d # which works fine
OrderedDict([('city', 'London'), ('pages', 200), ('item', 'book'), ('weight', 1.0), ('price', 25)])

Don't be confused by the output format! d is displayed as a list of pairs, passed to an OrderedDict constructor, for clarity. d isn't itself a list.

like image 79
Tim Peters Avatar answered Oct 25 '22 18:10

Tim Peters


no solution in Python 3.5


for python >= 3.6, just

Ordered_Dict = {k : Not_Ordered_Dict[k] for k in key_order}
like image 25
Chang Ye Avatar answered Oct 25 '22 20:10

Chang Ye