Lesson 3 • Intermediate

    Dictionaries in Python

    Store and access data using key-value pairs for fast and organized data management.

    What You'll Learn in This Lesson

    • What a dictionary is and how key-value pairs work
    • The difference between lists and dictionaries — when to use which
    • How to safely access values using .get() vs square brackets
    • How to add, update, and delete key-value pairs
    • How to loop through keys, values, and items
    • Nested dictionaries and real-world use cases

    1. What Are Dictionaries?

    A dictionary stores data in key-value pairs. Instead of accessing items by position (like lists), you access them by a unique key name.

    # Creating a dictionary
    person = {
    "name": "Alice",
    "age": 25,
    "city": "London"
    }

    Key Characteristics

    • Key-value pairs — Each item has a name (key) and data (value)
    • Fast lookups — Access any value instantly by its key
    • Unique keys — Each key can only appear once
    • Mutable — You can add, change, or remove items
    • Ordered — Maintains insertion order (Python 3.7+)

    2. Lists vs Dictionaries

    Understanding when to use each:

    FeatureListDictionary
    Access byIndex (0, 1, 2...)Key name
    Syntax[item1, item2]{key: value}
    Best forOrdered collectionsNamed/labeled data
    Example useList of namesUser profile info
    List (access by position)
    fruits = ["apple", "banana"]
    print(fruits[0])  # apple
    Dictionary (access by name)
    person = {"name": "Alice"}
    print(person["name"])  # Alice

    3. Creating Dictionaries

    MethodExampleDescription
    Empty dictionarymy_dict = {}Start with nothing
    With data{"key": "value"}Key-value pairs
    Using dict()dict(name="Alice")Constructor function

    Try It: Creating Dictionaries

    Different ways to create dictionaries

    Try it Yourself »
    Python
    # Different ways to create dictionaries
    
    # Empty dictionary
    my_dict = {}
    print("Empty:", my_dict)
    
    # Dictionary with data
    person = {
        "name": "Alice",
        "age": 25,
        "city": "London"
    }
    print("Person:", person)
    
    # Using dict() constructor
    info = dict(name="Bob", age=30, job="Developer")
    print("Info:", info)
    
    # Mixed value types
    product = {
        "id": 101,
        "name": "Laptop",
        "price": 999.99,
        "in_stock": True
    }
    print("Product:", product)

    4. Accessing Values

    There are two ways to access dictionary values:

    MethodSyntaxIf Key Missing
    Square bracketsdict["key"]KeyError (crashes)
    .get() methoddict.get("key")Returns None (safe)
    .get() with defaultdict.get("key", "default")Returns your default

    Try It: Accessing Values

    Two ways to get dictionary values

    Try it Yourself »
    Python
    person = {"name": "Alice", "age": 25}
    
    # Method 1: Square brackets (fast but risky)
    print("Name:", person["name"])
    
    # Method 2: .get() method (safe)
    print("Age:", person.get("age"))
    
    # .get() with missing key
    print("Email:", person.get("email"))          # Returns None
    print("Email:", person.get("email", "N/A"))   # Returns "N/A"
    
    # Square brackets with missing key would crash:
    # print(person["email"])  # KeyError!

    5. Adding and Changing Items

    Dictionaries are mutable — you can add new key-value pairs or update existing ones using the same syntax:

    dict["key"] = value # Add new or update existing

    Try It: Adding and Changing

    Add new items or update existing ones

    Try it Yourself »
    Python
    person = {"name": "Alice"}
    print("Start:", person)
    
    # Add new key-value pair
    person["age"] = 25
    print("After adding age:", person)
    
    # Add another
    person["city"] = "London"
    print("After adding city:", person)
    
    # Change existing value
    person["age"] = 26
    print("After changing age:", person)
    
    # Add multiple with .update()
    person.update({"job": "Developer", "country": "UK"})
    print("After update:", person)

    6. Removing Items

    MethodWhat It DoesExample
    del dict["key"]Delete a specific keydel person["age"]
    .pop("key")Remove and return the valueage = person.pop("age")
    .popitem()Remove last inserted itemlast = person.popitem()
    .clear()Remove all itemsperson.clear()

    Try It: Removing Items

    Different ways to remove dictionary items

    Try it Yourself »
    Python
    person = {"name": "Alice", "age": 25, "city": "London"}
    print("Start:", person)
    
    # del - delete by key
    del person["city"]
    print("After del:", person)
    
    # pop - remove and get the value
    age = person.pop("age")
    print(f"Popped age: {age}")
    print("After pop:", person)
    
    # pop with default (safe)
    job = person.pop("job", "Not found")
    print(f"Popped job: {job}")

    7. Checking if a Key Exists

    Use in to check if a key exists before accessing it:

    Try It: Checking Keys

    Check if keys exist before accessing

    Try it Yourself »
    Python
    person = {"name": "Alice", "age": 25}
    
    # Check if key exists
    if "name" in person:
        print("Name found:", person["name"])
    
    if "email" in person:
        print("Email:", person["email"])
    else:
        print("Email not found")
    
    # Check if key does NOT exist
    if "phone" not in person:
        print("Phone number not stored")
    
    # Practical pattern: safe access
    key = "city"
    if key in person:
        print(f"{key}: {person[key]}")
    else:
        print(f"{key} is not in the dictionary")

    8. Looping Through Dictionaries

    Loop TypeWhat You GetSyntax
    Keys onlyEach keyfor key in dict:
    Values onlyEach valuefor val in dict.values():
    BothKey and valuefor key, val in dict.items():

    Try It: Looping

    Iterate over keys, values, or both

    Try it Yourself »
    Python
    person = {"name": "Alice", "age": 25, "city": "London"}
    
    # Loop through keys (default)
    print("Keys:")
    for key in person:
        print(f"  {key}")
    
    # Loop through values
    print("\nValues:")
    for value in person.values():
        print(f"  {value}")
    
    # Loop through key-value pairs (most common)
    print("\nKey-Value pairs:")
    for key, value in person.items():
        print(f"  {key}: {value}")

    9. Useful Dictionary Methods

    MethodWhat It ReturnsExample
    .keys()All keysperson.keys()
    .values()All valuesperson.values()
    .items()All key-value pairsperson.items()
    .get(key)Value or Noneperson.get("name")
    .update(dict2)Merges dict2 into dictperson.update({...})
    .copy()A copy of the dictnew = person.copy()
    len(dict)Number of pairslen(person)

    Try It: Dictionary Methods

    Common dictionary operations

    Try it Yourself »
    Python
    person = {"name": "Alice", "age": 25, "city": "London"}
    
    # Get all keys
    print("Keys:", list(person.keys()))
    
    # Get all values
    print("Values:", list(person.values()))
    
    # Get all items as tuples
    print("Items:", list(person.items()))
    
    # Count pairs
    print(f"Number of items: {len(person)}")
    
    # Make a copy
    person_copy = person.copy()
    person_copy["name"] = "Bob"
    print(f"Original name: {person['name']}")
    print(f"Copy name: {person_copy['name']}")

    10. Nested Dictionaries

    Dictionaries can contain other dictionaries (or lists) as values. This is useful for organizing complex data.

    Try It: Nested Dictionaries

    Dictionaries inside dictionaries

    Try it Yourself »
    Python
    # Nested dictionary - users with details
    users = {
        "user1": {
            "name": "Alice",
            "age": 25,
            "email": "alice@email.com"
        },
        "user2": {
            "name": "Bob",
            "age": 30,
            "email": "bob@email.com"
        }
    }
    
    # Access nested values
    print("User1 name:", users["user1"]["name"])
    print("User2 email:", users["user2"]["email"])
    
    # Loop through nested dict
    print("\nAll users:")
    for user_id, info in users.items():
        print(f"  {user_id}: {info['name']} ({info['
    ...

    11. Dictionary Comprehension (Advanced)

    Like list comprehension, you can create dictionaries in one line:

    # Syntax
    {key: value for item in iterable}

    Try It: Dictionary Comprehension

    Create dictionaries with one-line expressions

    Try it Yourself »
    Python
    # Create a dictionary of squares
    squares = {x: x**2 for x in range(1, 6)}
    print("Squares:", squares)
    
    # Create from two lists
    names = ["Alice", "Bob", "Charlie"]
    ages = [25, 30, 35]
    people = {name: age for name, age in zip(names, ages)}
    print("People:", people)
    
    # With condition
    even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
    print("Even squares:", even_squares)

    12. Common Mistakes to Avoid

    MistakeProblemSolution
    Accessing missing keydict["missing"]Use .get() or check with in
    Using list as key{[1,2]: "val"}Keys must be immutable (str, int, tuple)
    Using square brackets["key", "value"]Use curly braces {"key": "value"}
    Forgetting the colon{"name" "Alice"}Use {"name": "Alice"}
    Duplicate keys{"a": 1, "a": 2}Each key must be unique (last value wins)

    13. Practical Examples

    Example 1: User Profile

    User Profile

    Store and display user information

    Try it Yourself »
    Python
    # Store user information
    user = {
        "username": "alice123",
        "email": "alice@example.com",
        "age": 25,
        "is_verified": True
    }
    
    # Display profile
    print("=== User Profile ===")
    for key, value in user.items():
        print(f"{key}: {value}")
    
    # Update email
    user["email"] = "alice.new@example.com"
    print(f"\nUpdated email: {user['email']}")

    Example 2: Word Counter

    Word Counter

    Count occurrences of words

    Try it Yourself »
    Python
    # Count word occurrences
    text = "apple banana apple cherry banana apple"
    words = text.split()
    
    word_count = {}
    for word in words:
        if word in word_count:
            word_count[word] += 1
        else:
            word_count[word] = 1
    
    print("Word counts:")
    for word, count in word_count.items():
        print(f"  {word}: {count}")

    Example 3: Simple Contact Book

    Contact Book

    Simple contact management

    Try it Yourself »
    Python
    # Contact book
    contacts = {
        "Alice": "123-456-7890",
        "Bob": "234-567-8901",
        "Charlie": "345-678-9012"
    }
    
    # Look up a contact
    name = "Bob"
    if name in contacts:
        print(f"{name}'s number: {contacts[name]}")
    else:
        print(f"{name} not found")
    
    # Add new contact
    contacts["Diana"] = "456-789-0123"
    
    # List all contacts
    print("\nAll contacts:")
    for name, phone in contacts.items():
        print(f"  {name}: {phone}")

    Summary: Quick Reference

    OperationSyntaxExample
    Create{key: value}{"name": "Alice"}
    Access (unsafe)dict["key"]person["name"]
    Access (safe)dict.get("key")person.get("name")
    Add/Changedict["key"] = valperson["age"] = 25
    Removedel dict["key"]del person["age"]
    Check exists"key" in dict"name" in person
    Loopfor k, v in dict.items():for k, v in person.items():
    Lengthlen(dict)len(person)
    🎉

    Lesson 8 done — you can now model real-world data in Python!

    Dictionaries are how Python stores structured data — user profiles, API responses, config settings. You know how to create, access, update, loop, and nest them safely.

    🚀 Up next: File Handling — learn to save data permanently so it survives after your program closes.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service