VOOZH about

URL: https://www.geeksforgeeks.org/python/python-program-to-get-value-of-a-dictionary-given-by-index-of-maximum-value-of-given-key/

⇱ Get Value of a Dictionary Given by index of Maximum Value of Given Key - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Get Value of a Dictionary Given by index of Maximum Value of Given Key

Last Updated : 23 Jul, 2025

We are given a dictionary where the values are lists and our task is to update these lists based on the highest value in a specified key. i.e we need to find the maximum value in a given key and then use its index to fetch the corresponding value from another key. For example: d = {"a": [3, 8, 2], "b": [5, 1, 7], "c": [6, 4, 9]} , max_search = "c" and opt_key = "a" then output will be 2 as the maximum value in key "c" is 9, which is at index 2 and the value at index 2 in key "a" is 2 so the output is 2.

Using enumerate()

In this method we use enumerate() to find the index of the maximum value while iterating over the list as this avoids an extra search operation making it more efficient.


Output
2

Explanation:

  • enumerate(d[max_search]) pairs values with indices and max(..., key=lambda x: x[1]) finds the tuple with the highest value (2, 9) hence idx = 2 is extracted.
  • d[opt_key][2] gives 2 which is the final output

Using zip()

We can use zip() to pair indices with values and then find the maximum value efficiently, this method keeps track of indices without needing enumerate().


Output
2

Explanation:

  • zip(range(len(d[max_search])), d[max_search]) pairs indices with values and max(..., key=lambda x: x[1]) finds the tuple (2, 9) hence idx = 2 is extracted.
  • d[opt_key][2] gives 2 which is the final output.

Using max() and Indexing

We can use the max() function to find the highest value in the specified key and then we get its index using the index() method and use this index to fetch the corresponding value from the other key.


Output
2

Explanation:

  • max(d[max_search]) finds the max value in key "c" which is 9.
  • d[max_search].index(9) gets the index of 9 which is 2.
  • d[opt_key][2] retrieves the value at index 2 in key "a", which is 2.

Using List Comprehension and Sorting

We can use list comprehension to pair indices with values and then sort it based on values to get the maximum index.


Output
2

Explanation:

  • [(i, v) for i, v in enumerate(d[max_search])] creates pairs like [(0, 6), (1, 4), (2, 9)].
  • sorted(..., key=lambda x: x[1]) sorts by values: [(1, 4), (0, 6), (2, 9)].
  • [-1][0] gets the last (max value) tuple and extracts the index (2).
  • d[opt_key][2] retrieves 2, which is our result.
Comment