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:
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.
no solution in Python 3.5
for python >= 3.6, just
Ordered_Dict = {k : Not_Ordered_Dict[k] for k in key_order}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With