foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Python
  • Understand what dictionaries are and how they work
  • Create, access, and modify dictionary entries
  • Use dictionary methods effectively
  • Know when to use dictionaries vs other data structures

Dictionaries: Key-Value Pairs

Think about how a real dictionary works: you look up a word (the key) to find its definition (the value). You don't flip through every page – you go directly to the word you need. This is exactly how Python dictionaries work!

Lists and tuples are great when order matters or when you access items by position. But what if you want to store a person's information? With a list, you'd need to remember that index 0 is name, index 1 is age, index 2 is email... Confusing! Dictionaries let you use meaningful labels instead: person['name'], person['age'], person['email'].


What is a Dictionary?

A dictionary is an unordered collection of key-value pairs:


                  Dictionary Characteristics                      

                                                                  
    KEY-VALUE: Every item has a unique key linked to a value   
      person["name"] = "Alice"                                    
          ↑              ↑                                        
         KEY           VALUE                                      
                                                                  
    UNIQUE KEYS: Each key can only appear once                 
      Adding duplicate key overwrites the old value              
                                                                  
    MUTABLE: Can add, remove, or change items                  
                                                                  
    FAST LOOKUP: Access by key is extremely fast               
      (no matter how big the dictionary!)                         
                                                                  

Real-World Analogies

Real-World Dictionary Equivalent
Word dictionary {"python": "a programming language"}
Phone contacts {"Alice": "555-1234", "Bob": "555-5678"}
Product prices {"apple": 0.99, "banana": 0.59}
Game scores {"player1": 1500, "player2": 2300}
Student record {"name": "Alice", "age": 20, "grade": "A"}

Creating Dictionaries

Basic Dictionary Creation

# Empty dictionary
empty_dict = {}
also_empty = dict()

# Dictionary with initial values
person = {
    "name": "Alice",
    "age": 25,
    "city": "Paris"
}

# Keys can be different types (but must be immutable)
mixed = {
    "name": "Test",      # String key
    1: "one",            # Integer key
    (1, 2): "tuple key"  # Tuple key (tuples are immutable!)
}

#  Lists cannot be keys (they're mutable!)
# invalid = {[1, 2]: "error"}  # TypeError!

Visual Representation


                  Dictionary: person                              

                                                                  
                     
       KEY               VALUE                                
                     
     "name"      →  "Alice"                                   
     "age"       →   25                                       
     "city"      →  "Paris"                                   
                     
                                                                  
   Access: person["name"] → "Alice"                              
           person["age"]  → 25                                   
                                                                  

Accessing Dictionary Values

Using Square Brackets

person = {"name": "Alice", "age": 25, "city": "Paris"}

# Access existing key
name = person["name"]  # "Alice"
age = person["age"]    # 25

#  Accessing non-existent key raises KeyError!
# country = person["country"]  # KeyError: 'country'

Using get() - Safer Access

person = {"name": "Alice", "age": 25}

# get() returns None for missing keys (no error!)
country = person.get("country")
print(country)  # None

# Or provide a default value
country = person.get("country", "Unknown")
print(country)  # "Unknown"

# Existing keys work normally
name = person.get("name")
print(name)  # "Alice"

When to Use Each Method


              dict["key"] vs dict.get("key")                      

                                                                  
   dict["key"]:                                                  
    When you're SURE the key exists                            
    When missing key should be an error                        
    Raises KeyError if key is missing                          
                                                                  
   dict.get("key"):                                              
    When key might not exist                                   
    When you want a default value                              
    Returns None (or default) if missing                       
                                                                  

Modifying Dictionaries

Adding and Updating

person = {"name": "Alice", "age": 25}

# Add new key-value pair
person["email"] = "alice@example.com"
print(person)
# {'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}

# Update existing value
person["age"] = 26
print(person["age"])  # 26

# Update multiple at once
person.update({"city": "Paris", "age": 27})
print(person)
# {'name': 'Alice', 'age': 27, 'email': 'alice@example.com', 'city': 'Paris'}

Removing Items

person = {"name": "Alice", "age": 25, "city": "Paris", "email": "alice@ex.com"}

# del - Remove by key
del person["email"]
print(person)  # {'name': 'Alice', 'age': 25, 'city': 'Paris'}

# pop() - Remove and return value
age = person.pop("age")
print(age)     # 25
print(person)  # {'name': 'Alice', 'city': 'Paris'}

# pop() with default (no error if missing)
phone = person.pop("phone", "Not found")
print(phone)   # "Not found"

# popitem() - Remove and return last item (Python 3.7+)
item = person.popitem()
print(item)    # ('city', 'Paris')

# clear() - Remove all items
person.clear()
print(person)  # {}

Dictionary Methods

Essential Methods Overview

Method Description Example
get(key, default) Safe access with default d.get('x', 0)
keys() Get all keys d.keys()
values() Get all values d.values()
items() Get key-value pairs d.items()
update(dict2) Merge another dict d.update({'a': 1})
pop(key) Remove & return d.pop('key')
setdefault(key, val) Get or set if missing d.setdefault('x', [])
copy() Create shallow copy d.copy()
clear() Remove all items d.clear()

Using keys(), values(), items()

student = {"name": "Alice", "age": 20, "grade": "A"}

# Get all keys
print(list(student.keys()))    # ['name', 'age', 'grade']

# Get all values
print(list(student.values()))  # ['Alice', 20, 'A']

# Get all key-value pairs as tuples
print(list(student.items()))   # [('name', 'Alice'), ('age', 20), ('grade', 'A')]

Iterating Through Dictionaries

Iterate Over Keys (Default)

person = {"name": "Alice", "age": 25, "city": "Paris"}

for key in person:  # Same as: for key in person.keys()
    print(key)

# Output:
# name
# age
# city

Iterate Over Values

for value in person.values():
    print(value)

# Output:
# Alice
# 25
# Paris

Iterate Over Key-Value Pairs (Most Useful!)

for key, value in person.items():
    print(f"{key}: {value}")

# Output:
# name: Alice
# age: 25
# city: Paris

Checking Keys and Values

person = {"name": "Alice", "age": 25}

# Check if key exists
print("name" in person)     # True
print("email" in person)    # False

# Check if key doesn't exist
print("email" not in person)  # True

# Check if value exists (less common)
print("Alice" in person.values())  # True

# Conditional usage
if "email" in person:
    print(f"Email: {person['email']}")
else:
    print("No email on file")

Nested Dictionaries

Real-world data is often hierarchical:

# Company directory
company = {
    "engineering": {
        "Alice": {"role": "Lead", "salary": 100000},
        "Bob": {"role": "Developer", "salary": 80000}
    },
    "marketing": {
        "Carol": {"role": "Manager", "salary": 90000}
    }
}

# Access nested values
alice_role = company["engineering"]["Alice"]["role"]
print(alice_role)  # "Lead"

# Safe nested access
def safe_get(d, *keys):
    for key in keys:
        if isinstance(d, dict):
            d = d.get(key)
        else:
            return None
    return d

salary = safe_get(company, "engineering", "Alice", "salary")
print(salary)  # 100000

Visual: Nested Structure


                  Nested Dictionary: company                      

                                                                  
   company                                                        
    "engineering"                                             
       "Alice"                                               
          "role": "Lead"                                    
          "salary": 100000                                  
       "Bob"                                                 
           "role": "Developer"                               
           "salary": 80000                                   
    "marketing"                                               
        "Carol"                                               
            "role": "Manager"                                 
            "salary": 90000                                   
                                                                  

Practical Examples

Example 1: Word Counter

text = "the quick brown fox jumps over the lazy dog the fox"
words = text.split()

word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1

print("Word frequencies:")
for word, count in sorted(word_count.items()):
    print(f"  {word}: {count}")

# Most common word
most_common = max(word_count, key=word_count.get)
print(f"\nMost common: '{most_common}' ({word_count[most_common]} times)")

Example 2: Simple Contact Book

contacts = {}

def add_contact(name, phone, email=None):
    contacts[name] = {"phone": phone, "email": email}
    print(f" Added {name}")

def find_contact(name):
    if name in contacts:
        info = contacts[name]
        print(f" {name}:")
        print(f"   Phone: {info['phone']}")
        print(f"   Email: {info['email'] or 'Not provided'}")
    else:
        print(f" {name} not found")

# Usage
add_contact("Alice", "555-1234", "alice@email.com")
add_contact("Bob", "555-5678")

find_contact("Alice")
find_contact("Carol")

Example 3: Shopping Cart with Prices

# Product catalog
prices = {
    "apple": 0.99,
    "banana": 0.59,
    "orange": 1.29,
    "milk": 3.49
}

# Shopping cart
cart = {"apple": 3, "milk": 2, "banana": 6}

print(" Your Cart:")
print("-" * 30)

total = 0
for item, quantity in cart.items():
    if item in prices:
        subtotal = prices[item] * quantity
        total += subtotal
        print(f"{item:12} x{quantity:3}  ${subtotal:6.2f}")
    else:
        print(f"{item:12} - Price not found!")

print("-" * 30)
print(f"{'Total':12}       ${total:6.2f}")

When to Use Dictionaries


          Decision Guide: When to Use Dictionaries                

                                                                  
   USE DICTIONARIES when:                                      
     • Data has meaningful labels (name, age, score)             
     • You need fast lookup by key                               
     • Storing configurations or settings                        
     • Mapping relationships (user_id → user_data)               
     • Counting occurrences (word → count)                       
     • JSON-like data structures                                 
                                                                  
   USE LISTS instead when:                                     
     • Order matters and data has no labels                      
     • You need to access by position (index)                    
     • Storing homogeneous data (all same type)                  
                                                                  

Key Takeaways


                   Remember These Points                          

                                                                  
   Dictionaries store key-value pairs: {"key": value}          
                                                                  
   Keys must be unique and immutable (strings, numbers, tuples)
     Values can be anything                                       
                                                                  
   Access: dict["key"] or dict.get("key", default)             
     Use get() when key might not exist                          
                                                                  
   Mutable: add, update, delete items freely                   
                                                                  
   Iterate: for key, value in dict.items()                     
                                                                  
   Check membership: "key" in dict                             
                                                                  
   Fast lookup regardless of size!                             
                                                                  

What's Next?

You've mastered dictionaries – Python's most powerful data structure for storing labeled data! In the final lesson of this module, we'll explore sets – collections designed for unique items and mathematical set operations like union, intersection, and difference.

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service