1

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
The August
  • 469
  • 2
  • 7
  • 18
  • Possible duplicates (in combination): [How to sort keys of dict by values?](https://stackoverflow.com/q/37270095/4518341), [How to sort a list with two keys but one in reverse order?](https://stackoverflow.com/q/37693373/4518341) – wjandrea Mar 25 '22 at 15:38

1 Answers1

3
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

Marat
  • 15,215
  • 2
  • 39
  • 48