Learn the basics of Python dictionaries with this beginner-friendly guide. Understand key-value pairs, how to create, access, update, and manipulate dictionaries in Python with practical examples and coding tasks. Perfect for students and professionals to master Python dictionaries.
In Python, a dictionary is a collection of key-value pairs. Each key in a dictionary is unique, and it is associated with a value. Dictionaries are used to store data values like a map or a real-life dictionary where each word (key) has a definition (value). They are mutable, meaning you can change, add, or remove items after the dictionary is created.
Example:
Think of a Python dictionary like a real dictionary: each word (key) has a definition (value).
You create a dictionary using curly braces {}
with keys and values separated by a colon :
. Multiple key-value pairs are separated by commas.
# Creating a dictionary with student information
student = {
"name": "John", # Key: "name", Value: "John"
"age": 20, # Key: "age", Value: 20
"courses": ["Math", "Science"] # Key: "courses", Value: list of courses
}
You can access the value associated with a specific key by using square brackets []
or the get()
method.
# Accessing values
print(student["name"]) # Output: John
print(student.get("age")) # Output: 20
You can add a new key-value pair or update an existing one by assigning a value to the key.
# Adding a new key-value pair
student["grade"] = "A"
# Updating an existing value
student["age"] = 21
Trying to use a list as a key will cause an error because lists are not hashable.
Write a Python program that:
Example Output:
Person: {'name': 'Alice', 'age': 25}
Name: Alice
Write a Python program that:
Example Output:
Original Dictionary: {'name': 'John', 'country': 'USA'}
Updated Dictionary: {'name': 'John', 'country': 'USA', 'hobby': 'Reading'}
Tutorials, Roadmaps, Bootcamps & Visualization Projects