Python Dictionaries · Organize Data with Key-Value Pairs

Mingming Li — Click any blue heading below to expand the content.

What is a dictionary? A dictionary stores data in key-value pairs. Think of it like a real dictionary: you look up a word (key) to find its definition (value). Or like a phone book: name (key) → phone number (value).

Table of Contents

1. What is a dictionary?

A dictionary stores data in key-value pairs. Each key is unique and is used to access its corresponding value. Dictionaries are created using curly braces { }.

# Dictionary examples
student = {"name": "Alice", "age": 25, "grade": "A"}
person = {
    "first_name": "John",
    "last_name": "Doe",
    "age": 30,
    "city": "New York"
}
empty = {}

# Accessing values
print(student["name"])    # "Alice"
print(student["age"])     # 25
Key property: Dictionaries are changeable, do NOT allow duplicate keys, and are very fast for lookups. Keys must be immutable (strings, numbers, tuples). Values can be any type.

2. Dictionary operations and methods

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

# Safe access with get() (no error if key missing!)
print(student.get("name"))        # "Alice"
print(student.get("score"))       # None (no error!)
print(student.get("score", 0))    # 0 (default value)

# Adding or updating
student["city"] = "Boston"        # add new key
student["age"] = 26               # update existing key

# Removing items
del student["grade"]              # remove specific key
age = student.pop("age")          # remove and return value
last_item = student.popitem()     # remove and return last item

# Other useful methods
student.clear()                   # remove all items
keys = student.keys()             # get all keys
values = student.values()         # get all values
items = student.items()           # get all key-value pairs
len(student)                      # number of items

# Check if key exists
if "name" in student:
    print("Name exists!")
Pro tip: Use .get() instead of [] when you're not sure if a key exists. It won't crash your program!

3. Looping through dictionaries

student = {"name": "Alice", "age": 25, "city": "Boston"}

# Loop through keys
for key in student:
    print(key, student[key])

# Loop through values
for value in student.values():
    print(value)

# Loop through key-value pairs (MOST USEFUL!)
for key, value in student.items():
    print(f"{key}: {value}")

# Dictionary comprehension
squares = {x: x*x for x in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Remember: .items() gives you both key and value at the same time. It's the most common way to loop through dictionaries!

4. Nested dictionaries

Dictionaries can contain other dictionaries. This is great for complex data like game characters, students, or settings.

# Nested dictionary example
students = {
    "student1": {"name": "Alice", "age": 20, "grade": "A"},
    "student2": {"name": "Bob", "age": 22, "grade": "B"},
    "student3": {"name": "Charlie", "age": 21, "grade": "A"}
}

# Accessing nested values
print(students["student1"]["name"])    # "Alice"
print(students["student2"]["grade"])   # "B"

# Looping through nested dictionary
for student_id, info in students.items():
    print(f"{student_id}: {info['name']} - {info['grade']}")

# Game character example
game = {
    "player": {"name": "Hero", "health": 100, "position": (10, 20)},
    "enemies": [{"name": "Goblin", "health": 30}, {"name": "Orc", "health": 50}],
    "score": 0,
    "active": True
}
Nested dictionaries are perfect for representing real-world objects with multiple properties. Think: a student has a name, age, and grades. A game character has health, position, and inventory.

5. Dictionary vs List - When to use which?

FeatureDictionaryList
IndexingKeys (any immutable type)Integers (0, 1, 2...)
Access speedVery fast (hash table)Fast
When to useLookup by name/label, fast searchesOrdered sequences, simple lists
MemoryMore memoryLess memory
# When to use dictionary:
student_grades = {"Alice": 85, "Bob": 92, "Charlie": 78}  # lookup by name

# When to use list:
scores = [85, 92, 78]   # simple ordered collection

# Converting between list and dictionary
keys = ["a", "b", "c"]
values = [1, 2, 3]
dictionary = dict(zip(keys, values))   # {'a': 1, 'b': 2, 'c': 3}
Rule of thumb: Use dictionaries when you need to look things up by a NAME (like a player's name or ID). Use lists when order matters or you just need a simple sequence.

6. Common dictionary patterns

# Counting letters (most common use case!)
word = "hello world"
char_count = {}
for char in word:
    char_count[char] = char_count.get(char, 0) + 1
print(char_count)   # {'h':1, 'e':1, 'l':3, 'o':2, ' ':1, 'w':1, 'r':1, 'd':1}

# Using defaultdict (even easier!)
from collections import defaultdict
counts = defaultdict(int)   # default value is 0
counts["apple"] += 1        # works even if "apple" didn't exist!

# Merging dictionaries (Python 3.5+)
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2}   # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Using update() method
dict1.update(dict2)   # adds dict2's items to dict1
Counting with dictionaries is extremely useful! The pattern dict[key] = dict.get(key, 0) + 1 is a classic.

7. Quick reference

# CREATING
d = {}                            # empty dictionary
d = {"key": "value"}              # with items
d = dict(name="Alice", age=25)    # using dict() constructor

# ACCESSING
d["key"]                          # access (raises KeyError if missing)
d.get("key")                      # access (returns None if missing)
d.get("key", default)             # with default value

# ADDING/UPDATING
d["new_key"] = "new_value"        # add or update
d.update({"k1": 1, "k2": 2})     # merge another dictionary

# REMOVING
del d["key"]                      # remove key
value = d.pop("key")              # remove and return value
d.popitem()                       # remove and return last item
d.clear()                         # remove all items

# CHECKING
"key" in d                        # check if key exists
len(d)                            # number of items

# ITERATING
for key in d:                     # loop through keys
for value in d.values():          # loop through values
for key, value in d.items():      # loop through pairs (BEST!)

# COMPREHENSION
squares = {x: x*x for x in range(5)}   # {0:0, 1:1, 2:4, 3:9, 4:16}

8. Quick Challenge: Dictionary Detective

Look at this code from our game. Can you spot the dictionary?

# In our game, we could store player stats in a dictionary
player = {
    "name": "Runner",
    "score": 0,
    "high_score": 0,
    "position": (80, 300),
    "is_alive": True
}

# Access player's score
print(f"Score: {player['score']}")

# Update score
player['score'] += 10
Click for questions
  • What are the keys in this dictionary?
  • How would you access the player's name?
  • How would you add a new key "level" with value 1?
  • How would you check if the player has a "health" key?
Click for answers
  • Keys: "name", "score", "high_score", "position", "is_alive"
  • player["name"] or player.get("name")
  • player["level"] = 1
  • if "health" in player: or player.get("health")

9. Exercises

Try these exercises to practice dictionaries. Write your code in Thonny.

  • Exercise 1: Create a student dictionary with keys "name", "age", "major". Print the name.
  • Exercise 2: Add "grade" = "A" and update age to 21.
  • Exercise 3: Remove "city" from person = {"name":"John", "age":30, "city":"NYC"}.
  • Exercise 4: Create a fruit-color dictionary (apple:red, banana:yellow). Loop and print each.
  • Exercise 5: Count letter frequencies in "mississippi".
  • Exercise 6: Merge dict1={"a":1,"b":2} and dict2={"c":3,"d":4}.
  • Exercise 7: Check if "apples" exists in inventory = {"apples":10, "bananas":5}.
  • Exercise 8: Find student with highest score from {"Alice":85, "Bob":92, "Charlie":78}.
  • Exercise 9: Use dict comprehension for cubes of numbers 1-10.
  • Exercise 10: Calculate average grade from {"Alice":85, "Bob":92, "Charlie":78, "Diana":95}.
  • Exercise 11: Create a game character dictionary with name, health, inventory list, position tuple.
  • Exercise 12: Create a phone book, add 3 contacts, loop to print all.

10. Common Errors & Solutions

  • KeyError: 'key_name'
    -> You tried to access a key that doesn't exist. Use .get() instead of [] when unsure.
  • TypeError: unhashable type: 'list'
    -> You tried to use a list as a dictionary key! Keys must be immutable (strings, numbers, tuples).
  • AttributeError: 'dict' object has no attribute 'append'
    -> Dictionaries don't have append. Use dict[key] = value to add items.
  • Dictionary changed size during iteration
    -> You tried to add/remove items while looping. Loop over list(dict.keys()) instead.
  • NameError: name 'defaultdict' is not defined
    -> You forgot to import: from collections import defaultdict
Debugging tip: Use print(dict.keys()) to see all keys. Use if key in dict: before accessing.

11. Check Your Understanding

  1. How do you create an empty dictionary?
  2. How do you access a value using its key?
  3. What is the difference between dict[key] and dict.get(key)?
  4. How do you add a new key-value pair?
  5. How do you loop through both keys and values?
  6. Can you use a list as a dictionary key? Why or why not?
Click for Answers
  1. d = {} or d = dict()
  2. dict[key]
  3. dict[key] raises KeyError if missing; .get() returns None (or a default).
  4. dict["new_key"] = value
  5. for key, value in dict.items():
  6. No! Lists are mutable (can change), so they can't be used as keys. Use tuples instead.

12. Your Progress Tracker

Check off each item as you master it:
I can create dictionaries with key-value pairs
I can access values using keys
I can use .get() to safely access values
I can add, update, and remove key-value pairs
I can loop through dictionaries with .items()
I can create nested dictionaries
I know when to use a dictionary vs a list
I can count frequencies using a dictionary
I completed at least 8 exercises