1

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'}

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • And your question is why with your code you get the same dictionary again instead? – mkrieger1 Jul 29 '22 at 12:30
  • Yes exactly. Following the two below above I am able to create a OrderedDict, all good but then if cast this back to a regular "dict" I get the initial sorting of the keys:values. – Nicola Orlando Jul 29 '22 at 12:59

2 Answers2

2

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'}
0

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