Sort dictionary with alphanumeric keys in natural order

I have a python dictionary:

d = {'a1': 123, 'a2': 2, 'a10': 333, 'a11': 4456} 

When I sort the dictionary using OrderedDict , I get the following output:

 from collections import OrderedDict OrderedDict(sorted(d.items())) # Output # OrderedDict([('a1', 123), ('a10', 333), ('a11', 4456), ('a2', 2)]) 

Is there a way to get it in natural order:

 OrderedDict([('a1', 123), ('a2', 2), ('a10', 333), ('a11', 4456)]) or {'a1': 123, 'a2': 2, 'a10': 333, 'a11': 4456} 

Thanks.

-1
source share
2 answers

You're in luck: the natsort module can help. First install it using:

 pip install natsort 

Now you can pass d.keys() to natsort.natsorted and build a new OrderedDict .

 import natsort from collections import OrderedDict d = {'a1' : 123, 'a2' : 2, 'a10': 333, 'a11': 4456} keys = natsort.natsorted(d.keys()) d_new = OrderedDict((k, d[k]) for k in keys) 

A shorter version includes sorting d.items() (got this idea from RomanPerekhrest answer ):

 d_new = OrderedDict(natsort.natsorted(d.items())) 

 d_new OrderedDict([('a1', 123), ('a2', 2), ('a10', 333), ('a11', 4456)]) 
+5
source

A short "trick" with the chr() function on the character code (without external packages):

 import collections d = {'a1': 123, 'a2': 2, 'a10': 333, 'a11': 4456} result = collections.OrderedDict(sorted(d.items(), key=lambda x: chr(int(x[0][1:])))) print(result) 

Output:

 OrderedDict([('a1', 123), ('a2', 2), ('a10', 333), ('a11', 4456)]) 
0
source

All Articles