python max key code example

Example 1: python find the key with max value

a_dictionary = {"a": 1, "b": 2, "c": 3}

# get key with max value
max_key = max(a_dictionary, key=a_dictionary.get)

print(max_key)

Example 2: python max key dictionary key getter

from operator import itemgetter

items = [
    {'a': 1, 'b': 99},
    {'a': 2, 'b': 88},
    {'a': 3, 'b': 77},
]

print(max(items, key=itemgetter('a')))
print(max(items, key=itemgetter('b')))

Example 3: python max function

square = {2: 4, -3: 9, -1: 1, -2: 4}

# the largest key
key1 = max(square)
print("The largest key:", key1)    # 2

# the key whose value is the largest
key2 = max(square, key = lambda k: square[k])

print("The key with the largest value:", key2)    # -3

# getting the largest value
print("The largest value:", square[key2])    # 9

Example 4: python max()

i = max(2, 4, 6, 3)

print(i)
# Result will be 6 because it is the highest number

Example 5: max function python

max([2, 1, 4, 3])