Skip to main content

Python Dictionaries: The Complete Guide with Real Examples

Beginner30 min8 exercises110 XP
0/8 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
Loading editor...

Keys are usually strings, but they can be any immutable type — numbers, tuples, or booleans. Values can be anything — strings, numbers, lists, even other dictionaries.

Mixed value types and empty dicts
Loading editor...

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
Loading editor...
Safe access with get()
Loading editor...
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()
Loading editor...
pop() and update()
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...
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
    Loading editor...
    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'}
    Loading editor...
    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
    Loading editor...
    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.

    Loading editor...
    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.

    Loading editor...
    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!
    Loading editor...
    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}
    Loading editor...
    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
    Loading editor...

    Summary: What You Learned About Python Dictionaries

    Great work! Here's a recap of everything you now know:
    ---------
    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](/python/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.