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

Sort python dict by two values

I’ve the following dict of list

d = {
    'k1':['EKAD', 444.2089, 121],
    'k2':['EKADD', 559.2358, 121],
    'k3':['KADDLG', 600.2988, 122],
    'k4':['ADDLGKG', 657.3202, 123]}

I wish to get the keys sorted first by value[2] then by length of value[0] string and in reverse order, i.e. the output will be k2, k1, k3, k4.

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

>Solution :

sorted(d, key=lambda x: (d[x][2], -len(d[x][0])))

Explanation:

Iteration over dictionaries returns keys. So, sorted(d, ...) will return keys sorted by the key criteria

key lambda generates tuples that will be used for comparison in sort. Tuples are compared using first element, then second, etc. If tuple is used as a key, it will sort using the first element (x[2]), then second (length of the first string), etc.

To reverse order on the length, but not on the numeric value, the length is negated

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