Key of Max Value

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, dictionaries are a useful data structure that allows you to store key-value pairs. Sometimes, you may need to find the key of the maximum value in a dictionary. In this challenge, you will write a function that takes a dictionary as an argument and returns the key of the maximum value in the dictionary.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13677{{"`Key of Max Value`"}} python/tuples -.-> lab-13677{{"`Key of Max Value`"}} python/dictionaries -.-> lab-13677{{"`Key of Max Value`"}} python/function_definition -.-> lab-13677{{"`Key of Max Value`"}} python/build_in_functions -.-> lab-13677{{"`Key of Max Value`"}} end

Key of Max Value

Write a function key_of_max(d) that takes a dictionary d as an argument and returns the key of the maximum value in the dictionary. If there are multiple keys with the same maximum value, return any one of them.

To solve this problem, you can use the max() function with the key parameter set to dict.get(). This will return the key of the maximum value in the dictionary.

def key_of_max(d):
  return max(d, key = d.get)
key_of_max({'a':4, 'b':0, 'c':13}) ## c

Summary

In this challenge, you learned how to find the key of the maximum value in a dictionary using Python. You can use the max() function with the key parameter set to dict.get() to find and return the key of the maximum value in the given dictionary.

Other Python Tutorials you may like