Back to: Python Programming
A dictionary is one of the four basic collection types. A dictionary consists of key:value pairs, they are ordered and changeable, no duplicates allowed.
# dictionary = a collection of {key:value} pairs
# ordered and changeable. No duplicates
capitals = {"USA": "Washington D.C.",
"India": "New Delhi",
"China": "Beijing",
"Russia": "Moscow"}
# print(dir(capitals)) # <-- ALL attributes and methods
# print(help(capitals))
# print(capitals.get("USA")) # <-- key exists so returns value
# print(capitals.get("Japan")) # <-- key doesn't exist, returns none
if capitals.get("Japan"):
print("That capital exists")
else:
print("That capital doesn't exist")
capitals.update({"Germany": "Berlin"}) # <-- adds "key:value" pair
# capitals.update({"USA": "Detroit"}) # <-- updates existing
# capitals.pop("China") # <-- removes a "key:value" pair
# capitals.popitem() # <-- removes latest "key:value" pair
# capitals.clear() # <-- clear entire dictionary
keys = capitals.keys() # <-- collects just "keys" into a list
for key in capitals.keys():
print(key)
# values = capitals.values()
# for value in capitals.values():
# print(value)
# items = capitals.items()
# print(items) # <-- output resembles a 2D list of tuples
# for key, value in capitals.items():
# print(f"{key}: {value}")
Example
Get key with maximum value in Dictionary
Given a dictionary, our task is to find the key having the maximum value. For Example: We are given a dictionary cars = {‘Audi’:100, ‘BMW’:1292, ‘Jaguar’: 210000, ‘Hyundai’ : 88} then the output will be Jaguar as it is the key with maximum value in dictionary.
Using max() with a Key Function
In this method we will use the built-in max() function to identify the key with the highest value in the dictionary and by specifying key=cars.get we can ensure that the comparison is based on the dictionary values rather than the keys.
cars = {'Audi':100, 'BMW':1292, 'Jaguar': 210000, 'Hyundai' : 88}
rating = max(cars, key=cars.get)
print(rating)
Outputs: Jaguar
Explanation: max() function is used to find the maximum element where key=car.get ensures the comparison is made based on the values (not keys).
Using sorted()
We use the sorted() function to sort the dictionary by its values in descending order and then pick the first key from the sorted list which will correspond to the maximum value.
cars = {'Audi':100, 'BMW':1292, 'Jaguar': 210000, 'Hyundai' : 88}
rating = sorted(cars, key=cars.get, reverse=True)[0]
print(rating)
Outputs: Jaguar
Explanation: sorted() function sorts the dictionary keys based on their values using key=d.get and setting reverse=True to sort in descending order and the first key in the sorted list is the one with the highest value.
Using a Loop
We iterate through each key-value pair in the dictionary comparing the value of each pair with the current maximum value. The key with the highest value is stored and returned at the end of the loop.
cars = {'Audi':100, 'BMW':1292, 'Jaguar': 210000, 'Hyundai' : 88}
max_key = None
max_value = float('-inf')
for k, v in cars.items():
if v > max_value:
max_value = v
max_key = k
print(max_key)
Dictionary Comprehension – Create Complex Data Structures Step by Step – (21m:57s)