python - Sorting dictionary with alphanumeric keys in natural order -
this question has answer here:
i have python dictionary:
d = {'a1': 123, 'a2': 2, 'a10': 333, 'a11': 4456} when sort dictionary using ordereddict following output:
from collections import ordereddict ordereddict(sorted(d.items())) # output # ordereddict([('a1', 123), ('a10', 333), ('a11', 4456), ('a2', 2)]) is there way in natural order:
ordereddict([('a1', 123), ('a2', 2), ('a10', 333), ('a11', 4456)]) or {'a1': 123, 'a2': 2, 'a10': 333, 'a11': 4456} thanks.
you're in luck: natsort module can help. first, install using:
pip install natsort now, can pass d.keys() natsort.natsorted, , build new ordereddict.
import natsort collections import ordereddict d = {'a1' : 123, 'a2' : 2, 'a10': 333, 'a11': 4456} keys = natsort.natsorted(d.keys()) d_new = ordereddict((k, d[k]) k in keys) a shorter version involves sorting d.items() (got idea romanperekhrest's answer):
d_new = ordereddict(natsort.natsorted(d.items())) d_new ordereddict([('a1', 123), ('a2', 2), ('a10', 333), ('a11', 4456)])
Comments
Post a Comment