Changing keys position dictionary

Viewed 32

I am trying to find a way to change the order of the entries in a python dictionary. I start with something like

{'first_name': 'Jack', 'age': '40', 'second_name': 'Sparrow', 'encounter_time': '10/May/2022'}

I would like something like

{'first_name': 'Jack', 'second_name': 'Sparrow', 'age': '40', 'encounter_time': '10/May/2022'}

2 Answers

By going through some old post I came across the question same as this one.

from collections import OrderedDict
kv = OrderedDict({'first_name': 'Jack', 'age': '40', 'second_name': 'Sparrow', 'encounter_time': '10/May/2022'})
order = ['first_name', 'second_name', 'age', 'encounter_time']

for key in order:
   kv.move_to_end(key)
print(kv)
print(dict(kv))

Output

OrderedDict([('first_name', 'Jack'), ('second_name', 'Sparrow'), ('age', '40'), ('encounter_time', '10/May/2022')])
{'first_name': 'Jack', 'second_name': 'Sparrow', 'age': '40', 'encounter_time': '10/May/2022'}

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({'first_name': 'Jack', 'age': '40', 'second_name': 'Sparrow', 'encounter_time': '10/May/2022'})
d # keeps the insertion order
OrderedDict([('first_name', 'Jack'), ('age', 40), ('second_name', 'Sparrow'), ('encounter_time', '10/May/2022')])
key_order= ['first_name', 'second_name', 'age', 'encounter_time'] # 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({'first_name': 'Jack', 'second_name': 'Sparrow', 'age': '40', 'encounter_time': '10/May/2022'})

See also this answer See also this answer

Related