Home > Mobile >  Sort python dict by two values
Sort python dict by two values

Time:03-26

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.

CodePudding user response:

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

  • Related