0
0
Pythonprogramming~5 mins

Accessing values using keys in Python

Choose your learning style9 modes available
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.
When you have a list of items with names and you want to find the price of a specific item.
When you store user information like name and age, and want to get the age using the name.
When you keep settings in a program and want to check the value of a particular setting.
When you have a phone book stored as names and numbers and want to find a number by name.
Syntax
Python
value = dictionary[key]
The key must exist in the dictionary, or Python will give an error.
Keys are usually strings or numbers, and they are unique in the dictionary.
Examples
Get the price of 'apple' from the prices dictionary.
Python
prices = {'apple': 2, 'banana': 1}
print(prices['apple'])
Access the 'age' value from the person dictionary.
Python
person = {'name': 'Anna', 'age': 30}
age = person['age']
print(age)
Retrieve the brightness setting value.
Python
settings = {'volume': 10, 'brightness': 70}
print(settings['brightness'])
Sample Program
This program shows how to get and print values from a dictionary using keys.
Python
student = {'name': 'John', 'grade': 'A', 'age': 16}
print(f"Name: {student['name']}")
print(f"Grade: {student['grade']}")
print(f"Age: {student['age']}")
OutputSuccess
Important Notes
If you try to access a key that does not exist, Python will raise a KeyError.
You can use the get() method to avoid errors and provide a default value if the key is missing.
Keys must be immutable types like strings, numbers, or tuples.
Summary
Use keys to quickly find values in a dictionary.
Keys must exist or use get() to avoid errors.
Dictionaries store data in key-value pairs for easy access.