Python Sorting in a List of Dictionaries by Numbers

I have a list of dictionaries that I’m trying to sort. This is what I have so far:

output_list = [{'interface': '0/20', 'mac': '01:23:45:67:89:AB'},
               {'interface': '0/16', 'mac': '12:34:56:78:9A:BC'},
               {'interface': '0/31', 'mac': '23:45:67:89:AB:CD'},
               {'interface': '0/5', 'mac': '34:56:78:9A:BC:DE'},
               {'interface': '0/3', 'mac': '45:67:89:AB:CD:EF'}]

mac_list = sorted(output_list, key=lambda d: d['interface'])

pprint(mac_list)

However, it’s not sorting the dictionaries the way I want.

"C:\Program Files\Python310\python.exe" "C:/Scripts/Python/test1.py"
[{'interface': '0/16', 'mac': '12:34:56:78:9A:BC'},
 {'interface': '0/20', 'mac': '01:23:45:67:89:AB'},
 {'interface': '0/3', 'mac': '45:67:89:AB:CD:EF'},
 {'interface': '0/31', 'mac': '23:45:67:89:AB:CD'},
 {'interface': '0/5', 'mac': '34:56:78:9A:BC:DE'}]

Process finished with exit code 0

How can I get it to sort it so it looks like this:

[{'interface': '0/3', 'mac': '45:67:89:AB:CD:EF'},
 {'interface': '0/5', 'mac': '34:56:78:9A:BC:DE'},
 {'interface': '0/16', 'mac': '12:34:56:78:9A:BC'},
 {'interface': '0/20', 'mac': '01:23:45:67:89:AB'},
 {'interface': '0/31', 'mac': '23:45:67:89:AB:CD'}]

>Solution :

You need to get the number out of the string:

sorted(output_list, key=lambda d: int(d['interface'].split("/")[1]))

This assumes that the first part of the interface won’t change.

If it changes, you need to reformat both parts with the leading zero:

sorted(output_list, key=lambda d: "/".join([f"{int(x):02d}" for x in d['interface'].split("/")]))

Leave a Reply