-3

I have a dictionary, where each key maps to an array. I want to sort the dictionary based on the highest value in the array of each key.

For example, the dictionary:

{'r': [2, 2], 'e': [4, 5], 't': [1, 1], 'h': [2, 2], 'y': [1, 2], 's': [0, 1], 'a': [0, 1]}

should become:

{ 'e': [4, 5], 'h': [2, 2], 'y': [1, 2], 'r': [2, 2], 't': [1, 1], 's': [0, 1], 'a': [0, 1]|
Perplexityy
  • 561
  • 1
  • 9
  • 26
  • 1
    Which version of Python is this? CPython versions before 3.6 do not have ordered built-in dictionaries and you would have to use `collections.OrderedDict` – Iain Shelvington Jul 18 '20 at 02:44
  • SO is not a code-writing service. What have you already tried, and where are you stuck? See [ask] if you want more advice. – wjandrea Jul 18 '20 at 02:48
  • 2
    Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value), [Find the greatest number in a list of numbers](https://stackoverflow.com/q/3090175/4518341) – wjandrea Jul 18 '20 at 02:49

1 Answers1

1
d = {'r': [2, 2], 'e': [4, 5], 't': [1, 1], 'h': [2, 2], 'y': [1, 2], 's': [0, 1], 'a': [0, 1]}

print({i: d[i] for i in sorted(d, key=lambda x: max(d[x]), reverse=True)})

and the result is:

{'e': [4, 5], 'r': [2, 2], 'h': [2, 2], 'y': [1, 2], 't': [1, 1], 's': [0, 1], 'a': [0, 1]}
Kevin Mayo
  • 1,089
  • 6
  • 19