Zhaoyu ZHONG Zhaoyu ZHONG - 1 year ago 44
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',

And my desired out put is:

sorted_dict_str = {'Number_1_item':'foo',

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.


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])))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download