0

My test dict is

d = {0:'5',28:'5', 23:'5', 21:'5'}

and I wrote the code

kk = {key:d[key] for key in sorted(d.keys())}

which shows the result

{0: '5', 28: '5', 21: '5', 23: '5'}

but I need

{0: '5', 21: '5', 23: '5', 28: '5'}

How can I get the desired result?

wovano
  • 4,543
  • 5
  • 22
  • 49

1 Answers1

0

In python, the dictionary data structure is not sequential. This means there are no differences between {0: 1, 1: 2} and {1: 2, 0: 1}. Of course, you can sort by keys if you get help from other types than dict, like a list of tuples, but there is another good data type that can be ordered.

from collections import OrderedDict
F.NiX
  • 1,457
  • 3
  • 12
  • 20