Introduction
You use keys to find and get the exact value you want from a collection called a dictionary. It helps you quickly find information without searching everything.
Jump into concepts and practice - no test required
value = dictionary[key]
prices = {'apple': 2, 'banana': 1}
print(prices['apple'])person = {'name': 'Anna', 'age': 30}
age = person['age']
print(age)settings = {'volume': 10, 'brightness': 70}
print(settings['brightness'])student = {'name': 'John', 'grade': 'A', 'age': 16}
print(f"Name: {student['name']}")
print(f"Grade: {student['grade']}")
print(f"Age: {student['age']}")'name' in the dictionary person = {'name': 'Alice', 'age': 30}?person and the key to access is 'name'.person['name'].'city' from dictionary data without causing an error if the key does not exist?data['city'] causes an error if the key is missing. Using data.get('city') returns None instead.get() method is designed to safely access keys without errors.info = {'a': 1, 'b': 2, 'c': 3}
print(info['b'])info has key 'b' with value 2.info['b'], which is 2.data = {'x': 10, 'y': 20}
print(data['z'])'z' is not present in data.KeyError.grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}, which code snippet correctly prints Bob's grade or 'Not found' if Bob is not in the dictionary?get() with default value, which is concise and safe. print(grades['bob'] or 'Not found') uses wrong key case and will fail. print(grades.get('Bob')) prints None if key missing, not 'Not found'.