sorting - Python order a dict by key value -
i've been trying order dict has keys format: "0:0:0:0:0:x" x variable incremented while filling dict.
since dictionaries doesn't insert in order, , need key-value values showed ordered, tried use
collections.ordereddict(sorted(observation_values.items()) where observation_values dict, values ordered caring first number, 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" "0:0:0:0:0:11" , again "0:0:0:0:0:110", ..:111, ..:112.
how can avoid using significant numbers order?
you sorting strings, sorted lexicographically, not numerically.
give sorted() custom sort key:
sortkey = lambda i: [int(e) e in i[0].split(':')] collections.ordereddict(sorted(observation_values.items(), key=sortkey)) this takes key of each key-value pair (i[0]), splitting on : colon , converting each number in key integer. keys sorted lexicographically across parts, , numerically per part; 0:0:0:0:0:1 sorts before 0:0:0:0:0:100 , both sort before 0:0:0:0:1:0.
Comments
Post a Comment