I was trying to sort a dict, where i had values such as:
‘e0’, ‘e3’, ‘e9’, …
but sadly python sorts it by "first letters", and when i have an ‘e12’ value it puts it before ‘e3’
can someone pls help me write a function which will sort it well
example dict for sorting:
{'e0': 50, 'e12': 89, 'e3': 110, 'e90': 18, 'e8': 82, 'e11': 40}
expected result:
{'e0': 50, 'e3': 110, 'e8': 82, 'e11': 40, 'e12': 89, 'e90': 18}
I’ve tried to do it sorted(); of course, it didn’t work, but I also tried
sorted(thedict.items(), key=lambda x: int(x[0]))
but it doesn’t work correctly too (described in the beginning)
>Solution :
-
I’d save the keys as tuple
('e', 12), before creating thedict(). -
If that’s not an option, then you have to break it apart and get the number and sort it based on that:
def _sort_dict(d):
def _by_num(key):
return int(key[1:])
return dict(sorted(d.items(), key=lambda x: _by_num(x[0])))
print(_sort_dict({'e0': 50, 'e12': 89, 'e3': 110, 'e90': 18, 'e8': 82, 'e11': 40}))
Prints
{‘e0’: 50, ‘e3’: 110, ‘e8’: 82, ‘e11’: 40, ‘e12’: 89, ‘e90’: 18}
Note
- If the alpha part was longer, we can get the ending digits:
import re
def _sort_dict(d):
def _by_num(key):
num = re.search(r'\d*$', key)[0]
return int(num) if num else -1
return dict(sorted(d.items(), key=lambda x: _by_num(x[0])))
print(_sort_dict({'eeee0': 50, 'eeee12': 89, 'eeee3': 110, 'ee90': 18, 'eaaa8': 82, 'ebbb11': 40, 'eeee': 50}))
Prints
{‘eeee’: 50, ‘eeee0’: 50, ‘eeee3’: 110, ‘eaaa8’: 82, ‘ebbb11’: 40,
‘eeee12’: 89, ‘ee90’: 18}
Note:
If you may have had, only alphas, or only numeric or both, you can use this pattern, r'(^[^0-9]*)(\d*)$', generate a tuple of (alpha, numeric) and then sort it:
Code
import re
def _sort_dict(d):
def _by_num(key):
p = r'(^[^0-9]*)(\d*)$'
alpha, num = re.findall(p, key)[0]
return (alpha, int(num if num else -1))
return dict(sorted(d.items(), key=lambda x: _by_num(x[0])))
print(_sort_dict({'eeee0': 50, 'eeee12': 89, 'eeee3': 110,
'ee90': 18, 'eaaa8': 82, 'ebbb11': 40, 'eeee': 50, '0': 50}))
Prints
{‘0’: 50, ‘eaaa8’: 82, ‘ebbb11’: 40, ‘ee90’: 18, ‘eeee’: 50, ‘eeee0’:
50, ‘eeee3’: 110, ‘eeee12’: 89}