Progress0%

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:

Python
1# A simple dictionary storing ages
2ages = {
3 "John": 25,
4 "Alice": 22,
5 "Bob": 30
6}

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:

Python
1# Creating an empty dictionary
2my_dict = {}
3
4# Creating a dictionary with initial values
5student = {
6 "name": "Alice",
7 "age": 20,
8 "grade": "A"
9}
10
11# Print the dictionary
12print(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:

Python
1# Create a dictionary
2student = {
3 "name": "Alice",
4 "age": 20,
5 "grade": "A"
6}
7
8# Method 1: Using square brackets
9name = student["name"]
10print(name) # Output: Alice
11
12# Method 2: Using get() method (safer)
13age = student.get("age")
14print(age) # Output: 20
15
16# Using get() with a default value
17score = student.get("score", 0) # Returns 0 if "score" doesn't exist
18print(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:

Python
1# Start with an empty dictionary
2student = {}
3
4# Adding new key-value pairs
5student["name"] = "Alice"
6student["age"] = 20
7
8# Update existing value
9student["age"] = 21
10
11print(student) # Output: {'name': 'Alice', 'age': 21}
12
13# Add multiple items at once using update()
14student.update({
15 "grade": "A",
16 "city": "London"
17})
18
19print(student) # Output: {'name': 'Alice', 'age': 21, 'grade': 'A', 'city': 'London'}

👋 Let's Practice!

Try these simple exercises to get comfortable with dictionaries:

Python
1# Exercise 1: Create a dictionary about your favorite book
2# Include: title, author, year, and rating
3
4# Exercise 2: Create a simple contact list
5contacts = {}
6# Add at least 3 contacts with their phone numbers
7# Update one contact's number
8# Print all contacts
9
10# Exercise 3: Create a mini library catalog
11# Store books with their status (available/borrowed)
12# Add functions to:
13# - Add new books
14# - Mark books as borrowed/returned
15# - Check if a book is available

Related Tutorials

Work with unordered collections of unique elements.

Learn more

Master sequence types in Python.

Learn more

Work with JSON data in Python.

Learn more