Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{'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("/")]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading