Zhaoyu ZHONG Zhaoyu ZHONG - 9 months ago 19
Python Question

How to sort a dictionary in Python with keys of mixed letters and numbers?

I have a dictionary like this:

dict_str = {'Number_1_item':'foo',
'Number_11_item':'bar',
'Number_22_item':'foobar',
'Number_5_item':'barfoo'}


And my desired out put is:

sorted_dict_str = {'Number_1_item':'foo',
'Number_5_item':'bar',
'Number_11_item':'foobar',
'Number_22_item':'barfoo'}


So the sorted_dict_str is sorted in numerical way based on the keys in dict_str.
I have found some answers to sort the keys with pure numeric keys but not mixed ones, so they are not really helpful.

Thanks a lot.

Regards

Answer Source

You can get sorted dict from your dict like that:

from collections import OrderedDict

OrderedDict(sorted(dict_str.items(), key=lambda s: int(s[0].split('_')[1])))