Skip to main content
Editor

Python Dictionaries: The Complete Guide with Real Examples

Beginner30 min9 exercises140 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/9 exercises

Open the contacts app on your phone. You look up a person by name and get their phone number. You don't search by position - you don't say "give me contact number 47." You search by name.

A Python dictionary works exactly like that. Instead of storing items by position (like a list), a dictionary stores items as key-value pairs. The key is the name you look up, and the value is what you get back.

Dictionaries are everywhere in real programming. User profiles, configuration settings, JSON data from APIs, word counters - they all use dictionaries. In this tutorial, you'll master every essential dictionary operation.

How to Create a Python Dictionary

You create a dictionary using curly braces {} with key-value pairs separated by colons. Each pair is separated by a comma.

Creating a dictionary
# A simple dictionary
contact = {
'name': 'Alice',
'phone': '555-1234',
'email': 'alice@example.com',
}
print(contact)
Output
{'name': 'Alice', 'phone': '555-1234', 'email': 'alice@example.com'}

Keys are usually strings, but they can be any hashable value (in practice, one that can't change), such as a number, a boolean, or a tuple of these. Values can be anything - strings, numbers, lists, even other dictionaries.

Mixed value types and empty dicts
# Different types of keys and values
student = {
'name': 'Bob',
'age': 16,
'grades': [85, 92, 78],
'active': True,
}
print(student)
# Empty dictionary - two ways
empty1 = {}
empty2 = dict()
print(empty1) # {}
print(empty2) # {}
Output
{'name': 'Bob', 'age': 16, 'grades': [85, 92, 78], 'active': True}
{}
{}

Accessing and Modifying Dictionary Values

To get a value from a dictionary, put the key inside square brackets. To change a value, assign to that key. To add a new pair, just assign to a key that doesn't exist yet.

Access, modify, and add values
person = {'name': 'Alice', 'age': 25, 'city': 'Boston'}
# Access a value by key
print(person['name']) # Alice
print(person['age']) # 25
# Change an existing value
person['age'] = 26
print(person['age']) # 26
# Add a new key-value pair
person['job'] = 'Engineer'
print(person)
Output
Alice
25
26
{'name': 'Alice', 'age': 26, 'city': 'Boston', 'job': 'Engineer'}
Safe access with get()
person = {'name': 'Alice', 'age': 25}
# This would crash:
# print(person['salary']) # KeyError!
# Safe way: use .get() with a default value
print(person.get('salary', 'Not specified')) # Not specified
print(person.get('name', 'Unknown')) # Alice
Output
Not specified
Alice
Unsafe: square brackets crash on missing key
data = {'x': 10}
# Crashes with KeyError:
value = data['y']
Safe: get() returns a default value
data = {'x': 10}
# Returns 0 if 'y' is missing:
value = data.get('y', 0)

Essential Dictionary Methods

Dictionaries come with several built-in methods that make them easy to work with. Here are the ones you'll use most often.

keys(), values(), and items()
fruit_prices = {'apple': 1.50, 'banana': 0.75, 'cherry': 3.00}
# keys() - get all keys
print(list(fruit_prices.keys())) # ['apple', 'banana', 'cherry']
# values() - get all values
print(list(fruit_prices.values())) # [1.5, 0.75, 3.0]
# items() - get all key-value pairs as tuples
print(list(fruit_prices.items())) # [('apple', 1.5), ('banana', 0.75), ('cherry', 3.0)]
Output
['apple', 'banana', 'cherry']
[1.5, 0.75, 3.0]
[('apple', 1.5), ('banana', 0.75), ('cherry', 3.0)]
pop() and update()
inventory = {'apples': 5, 'bananas': 3, 'oranges': 8}
# pop() - remove a key and return its value
removed = inventory.pop('bananas')
print(removed) # 3
print(inventory) # {'apples': 5, 'oranges': 8}
# update() - merge another dictionary into this one
inventory.update({'grapes': 12, 'apples': 10})
print(inventory) # {'apples': 10, 'oranges': 8, 'grapes': 12}
Output
3
{'apples': 5, 'oranges': 8}
{'apples': 10, 'oranges': 8, 'grapes': 12}

Notice that update() both adds new keys and overwrites existing ones. In the example above, 'apples' changed from 5 to 10, and 'grapes' was added as a new key.

Looping Through Dictionaries

You can loop through a dictionary's keys, values, or both. The most common approach is to loop through items() so you get both the key and value at once.

Three ways to loop through a dictionary
scores = {'Alice': 95, 'Bob': 87, 'Charlie': 72}
# Loop through keys (default)
for name in scores:
print(name)
print('---')
# Loop through values
for score in scores.values():
print(score)
print('---')
# Loop through both (most useful)
for name, score in scores.items():
print(f'{name}: {score}')
Output
Alice
Bob
Charlie
---
95
87
72
---
Alice: 95
Bob: 87
Charlie: 72

Checking if a Key Exists

Before accessing a key, you often want to check if it exists first. The in keyword checks for keys - not values.

Using in to check for keys
user = {'name': 'Alice', 'email': 'alice@example.com'}
# Check if a key exists
print('name' in user) # True
print('phone' in user) # False
print('phone' not in user) # True
# Common pattern: check before accessing
if 'email' in user:
print(f'Email: {user["email"]}')
else:
print('No email on file')
Output
True
False
True
Email: alice@example.com

Nested Dictionaries

A dictionary value can be another dictionary. This is called nesting and it lets you represent complex, structured data - like a classroom of students, each with their own set of attributes.

Nested dictionaries
classroom = {
'Alice': {'age': 16, 'grade': 'A'},
'Bob': {'age': 15, 'grade': 'B'},
'Charlie': {'age': 16, 'grade': 'A'},
}
# Access a nested value with chained brackets
print(classroom['Alice']['grade']) # A
print(classroom['Bob']['age']) # 15
# Loop through nested data
for name, info in classroom.items():
print(f'{name} is {info["age"]} and got a {info["grade"]}')
Output
A
15
Alice is 16 and got a A
Bob is 15 and got a B
Charlie is 16 and got a A

To access a nested value, you chain square brackets: first the outer key, then the inner key. You can nest as deep as you want, but more than two or three levels gets hard to read.

Common Mistakes with Dictionaries

Tuples as dictionary keys
# This works - tuples are immutable
locations = {
(40.71, -74.00): 'New York',
(51.50, -0.12): 'London',
}
print(locations[(40.71, -74.00)]) # New York
# This would crash:
# bad = {[1, 2]: 'nope'} # TypeError: unhashable type: 'list'
Output
New York
Crashes: modifying during loop
data = {'a': 1, 'b': 2, 'c': 3}
for key in data:
    if data[key] < 2:
        del data[key]  # RuntimeError!
Works: loop through a copy of keys
data = {'a': 1, 'b': 2, 'c': 3}
for key in list(data.keys()):
    if data[key] < 2:
        del data[key]  # Safe!
print(data)  # {'b': 2, 'c': 3}

Practice Exercises

Time to practice! These exercises progress from basic dictionary operations to more complex patterns.

Exercise 1: Create a Dictionary and Access a Value
Write Code

Create a dictionary called pet with these key-value pairs:

  • 'name': 'Buddy'
  • 'species': 'dog'
  • 'age': 5
  • Then print the pet's name.

    Expected output:

    Buddy
    # Create the pet dictionary
    # Print the pet's name
    Exercise 2: Add and Modify Dictionary Entries
    Write Code

    A dictionary representing a book is given. Do these steps in order:

    1. Change the 'year' to 2024

    2. Add a new key 'genre' with the value 'fiction'

    3. Print the entire dictionary

    Expected output:

    {'title': 'The Great Adventure', 'author': 'Jane Smith', 'year': 2024, 'genre': 'fiction'}
    book = {'title': 'The Great Adventure', 'author': 'Jane Smith', 'year': 2020}
    # Step 1: Change the year to 2024
    # Step 2: Add genre
    # Step 3: Print the dictionary
    Exercise 3: Safe Access with get()
    Write Code

    A user profile dictionary is given. Use the .get() method to safely print the user's phone number. If the key 'phone' doesn't exist, print 'No phone number'.

    Expected output:

    No phone number
    profile = {'name': 'Alice', 'email': 'alice@mail.com'}
    # Use .get() to safely access the phone key
    Exercise 4: Loop Through a Dictionary
    Write Code

    Loop through the dictionary and print each fruit and its price in this format:

    apple: $1.50
    banana: $0.75
    cherry: $3.00

    Make sure prices show exactly two decimal places.

    prices = {'apple': 1.5, 'banana': 0.75, 'cherry': 3.0}
    # Loop and print each item
    Exercise 5: Predict the Output: Duplicate Keys
    Predict Output

    Read this code carefully and predict what it will print. What happens when a dictionary has duplicate keys?

    Type the exact output.

    data = {'a': 1, 'b': 2, 'a': 3}
    print(data)
    print(len(data))
    Exercise 6: Fix the Bug: Checking for a Value
    Fix the Bug

    This code tries to check if the grade 'A' exists in the dictionary, but it's checking the wrong thing. Fix it so it prints:

    Someone got an A!
    grades = {'Alice': 'A', 'Bob': 'B', 'Charlie': 'C'}
    if 'A' in grades:
    print('Someone got an A!')
    else:
    print('No one got an A.')
    Exercise 7: Build a Word Counter
    Write Code

    Count how many times each word appears in the given list. Store the counts in a dictionary called word_counts, then print it.

    Expected output:

    {'hello': 3, 'world': 2, 'python': 1}
    words = ['hello', 'world', 'hello', 'python', 'hello', 'world']
    # Build a word count dictionary
    # Print the result
    Exercise 8: Access Nested Dictionary Data
    Write Code

    A nested dictionary of students is given. Loop through each student and print their name and math score in this format:

    Alice: 95
    Bob: 82
    Charlie: 91
    students = {
    'Alice': {'math': 95, 'english': 88},
    'Bob': {'math': 82, 'english': 90},
    'Charlie': {'math': 91, 'english': 85},
    }
    # Loop and print each student's math score
    First to the Top
    Stretch

    Votes are counted one at a time. Write a function winner(votes) that takes the list of names in the order they were counted and returns the name with the most votes. When there is a tie, the name that reached that number of votes first wins. With no votes, return None.

    winner(["ann", "bob", "ann"])                # 'ann'
    winner(["kim", "bob", "bob", "kim", "cy"])   # 'bob'

    In the second list kim and bob both get 2 votes, but bob reached 2 at the third vote and kim only at the fourth.

    Return the answer instead of printing it: Check calls winner() with its own votes, some of them hidden.

    def winner(votes):
    pass
    Solution unlocks after your first Check

    Summary: What You Learned About Python Dictionaries

    Great work! Here's a recap of everything you now know:

    ConceptWhat it doesExample
    Create a dictStore key-value pairsd = {'name': 'Alice'}
    Access by keyGet a valued['name']
    Safe accessDefault if missingd.get('x', 0)
    Add / modifySet a valued['age'] = 25
    keys()All keysd.keys()
    values()All valuesd.values()
    items()Key-value tuplesd.items()
    pop(key)Remove and returnd.pop('age')
    update()Merge dictsd.update(other)
    inCheck if key exists'name' in d
    NestingDicts inside dictsd['a']['b']

    Dictionaries are one of the most important data structures in Python. JSON data, API responses, configuration files, counters - they all revolve around key-value pairs.

    What's Next?

    In the next tutorial - Python Comprehensions - you'll learn how to create lists, dictionaries, and sets in a single elegant line of code.

    Comprehensions let you replace multi-line loops with concise one-liners. They're one of the features that makes Python feel so clean and expressive.

    Harder problems

    More problems on this topic: Dictionaries and sets

    Related Tutorials

    Was this tutorial helpful?