Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python order a dict by key value

I've been trying to order my dict that has keys with this format: "0:0:0:0:0:x" where x is the variable that get incremented while filling the dict.

Since dictionaries doesn't insert in order, and I need the key-value values to be showed ordered, I tried to use

collections.OrderedDict(sorted(observation_values.items())

where observation_values is my dict, but values are ordered caring about the first number, like this:

"0:0:0:0:0:0": [0.0], "0:0:0:0:0:1": [0.0], "0:0:0:0:0:10": [279.5],
"0:0:0:0:0:100": [1137.8], "0:0:0:0:0:101": [1159.4], "0:0:0:0:0:102":
[1180.3], "0:0:0:0:0:103": [1193.6]...

till "0:0:0:0:0:109" then back to "0:0:0:0:0:11" and then again "0:0:0:0:0:110", ..:111, ..:112.

How can I avoid using only most significant numbers to order?

like image 582
A. Martinelli Avatar asked Nov 20 '25 14:11

A. Martinelli


1 Answers

You are sorting strings, so they are sorted lexicographically, not numerically.

Give sorted() a custom sort key:

sortkey = lambda i: [int(e) for e in i[0].split(':')]
collections.OrderedDict(sorted(observation_values.items(), key=sortkey))

This takes the key of each key-value pair (i[0]), splitting it on the : colon and converting each number in that key to an integer. Now the keys will be sorted lexicographically across the parts, and numerically per part; now 0:0:0:0:0:1 sorts before 0:0:0:0:0:100 and both sort before 0:0:0:0:1:0.

like image 93
Martijn Pieters Avatar answered Nov 22 '25 04:11

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!