8 of 20 topics completed
Python Dictionaries
Think of a dictionary in Python like a real-world dictionary where you look up definitions. Instead of looking up word definitions, you can store and look up any kind of information using a unique "key".
For example, just like you look up the meaning of "apple" in a dictionary, in Python you can store and look up a person's age using their name as the key.
What You'll Learn
✏️ Basics
- • What dictionaries are and why they're useful
- • How to create and use dictionaries
- • Working with keys and values
🔧 Operations
- • Adding and updating items
- • Removing items
- • Common dictionary methods
Understanding Dictionaries
A dictionary is a collection of key-value pairs. Each key must be unique, but values can be repeated. Here's a simple example:
1# A simple dictionary storing ages2ages = {3 "John": 25,4 "Alice": 22,5 "Bob": 306}
In this example:
- • The names ("John", "Alice", "Bob") are the keys
- • The ages (25, 22, 30) are the values
- • Each key-value pair is separated by a comma
- • The entire dictionary is enclosed in curly braces
Creating Your First Dictionary
Let's start with the basics of creating dictionaries:
1# Creating an empty dictionary2my_dict = {}34# Creating a dictionary with initial values5student = {6 "name": "Alice",7 "age": 20,8 "grade": "A"9}1011# Print the dictionary12print(student) # Output: {'name': 'Alice', 'age': 20, 'grade': 'A'}
Important Notes:
- • Keys must be unique
- • Keys must be immutable (strings, numbers, or tuples)
- • Values can be of any type (numbers, strings, lists, other dictionaries)
Accessing Dictionary Values
There are two main ways to access values in a dictionary:
1# Create a dictionary2student = {3 "name": "Alice",4 "age": 20,5 "grade": "A"6}78# Method 1: Using square brackets9name = student["name"]10print(name) # Output: Alice1112# Method 2: Using get() method (safer)13age = student.get("age")14print(age) # Output: 201516# Using get() with a default value17score = student.get("score", 0) # Returns 0 if "score" doesn't exist18print(score) # Output: 0
🚨 Common Mistake to Avoid
Using square brackets [] with a non-existent key will raise an error. It's safer to use the get() method, which returns None or a default value if the key doesn't exist.
Adding and Updating Values
You can easily add new items or update existing ones:
1# Start with an empty dictionary2student = {}34# Adding new key-value pairs5student["name"] = "Alice"6student["age"] = 2078# Update existing value9student["age"] = 211011print(student) # Output: {'name': 'Alice', 'age': 21}1213# Add multiple items at once using update()14student.update({15 "grade": "A",16 "city": "London"17})1819print(student) # Output: {'name': 'Alice', 'age': 21, 'grade': 'A', 'city': 'London'}
👋 Let's Practice!
Try these simple exercises to get comfortable with dictionaries:
1# Exercise 1: Create a dictionary about your favorite book2# Include: title, author, year, and rating34# Exercise 2: Create a simple contact list5contacts = {}6# Add at least 3 contacts with their phone numbers7# Update one contact's number8# Print all contacts910# Exercise 3: Create a mini library catalog11# Store books with their status (available/borrowed)12# Add functions to:13# - Add new books14# - Mark books as borrowed/returned15# - Check if a book is available
Related Tutorials
Work with unordered collections of unique elements.
Learn moreMaster sequence types in Python.
Learn moreWork with JSON data in Python.
Learn more