anvd
anvd

Reputation: 4047

Order dictionary by key with numerical representation

I have this input, where each value has a range of 200:

d = {'600-800': 3, '1800-2000': 3, '1000-1200': 5, '400-600': 1, '2600-2800': 1}

And I am looking for this expected order:

{'400-600': 1, '600-800': 3, '1000-1200': 5, '1800-2000': 3, '2600-2800': 1}

Already tried something like this, but the order is just wrong:

import collections
od = collections.OrderedDict(sorted(d.items()))
print od

Upvotes: 2

Views: 59

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51683

You can split the key into parts at '-' and use the first part as integer value to sort it. The second part is irrelevant for ordering because of the nature of your key-values (when converted to integer):

d = {'600-800': 3, '1800-2000': 3, '1000-1200': 5, '400-600': 1, '2600-2800': 1}
import collections
od = collections.OrderedDict(sorted(d.items(),key =lambda x: int(x[0].split("-")[0])))
print od

Output:

OrderedDict([('400-600', 1), ('600-800', 3), ('1000-1200', 5), 
             ('1800-2000', 3), ('2600-2800', 1)])

Doku:

Related:

Upvotes: 4

Graipher
Graipher

Reputation: 7206

If you want to order your dictionary by the first year first (and then by the second year if needed, which is unnecessary in the given example, but feels more natural), you need to convert to integers and set a custom key:

d = {'600-800': 3, '1800-2000': 3, '1000-1200': 5, '400-600': 1, '2600-2800': 1}

sorted(d.items(), key=lambda t: tuple(map(int, t[0].split("-"))))
# [('400-600', 1),
#  ('600-800', 3),
#  ('1000-1200', 5),
#  ('1800-2000', 3),
#  ('2600-2800', 1)]

The conversion to integers is needed because e.g. "1000" < "200", but 1000 > 200. This list can be passed to OrderedDict afterwards like in your code, if needed.

Upvotes: 2

Related Questions