How do I arrange dict in key order?

Asked 1 years ago, Updated 1 years ago, 96 views

{2:3, 1:89, 4:5, 3:0 ->{1:89, 2:3, 3:0, 4:5} How do I arrange it in key order? In other articles, everyone returns the tuple with the ordered value. I need a dict, not a tuple

sorting python dictionary

2022-09-22 13:10

1 Answers

The Python standard dict type is unordered. Therefore, no matter how you sort the key-value values, you cannot save them as dict type while maintaining the order.

So, if you want to keep the order with dict, write OrderedDict in the collections module. *OrderedDict stores elements in the order they come in

import collections
d = {2:3, 1:89, 4:5, 3:0}
od = collections.OrderedDict(sorted(d.items())) #Sort and put it in the orderedDict in order
print od #OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
print od[1] #89
print od[3] #0

for k, v in od.iteritems(): print k, v

In #Python 3,
for k, v in od.items(): print k, v


2022-09-22 13:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.