KAHIBARO Bookshelves
Discord Login Register

8.3. Dictionaries

Understanding Dictionaries

Dictionaries are a built‑in Python data type that store key–value pairs. They are useful when you want to look up a value using some kind of label (the key), instead of using a numeric index like in lists.

Some everyday examples of dictionaries in real life:

  • A phone book: name → phone number
  • A word dictionary: word → definition
  • A student record: student ID → student information

In Python, a dictionary:

  • Uses {} (curly braces)
  • Contains pairs written as key: value
  • Uses unique keys (each key appears at most once)
  • Can store any kind of values (numbers, strings, lists, even other dictionaries)

Example:

student = {
    "name": "Alice",
    "age": 20,
    "is_student": True
}

Here "name", "age", and "is_student" are keys, and "Alice", 20, True are the values.

Creating Dictionaries

You can create dictionaries in several ways.

Using curly braces `{}`

The most common way:

person = {
    "first_name": "John",
    "last_name": "Doe",
    "age": 30
}

Keys are usually strings, but they can be many other types (with some rules; more on that later).

An empty dictionary:

empty_dict = {}

Using the `dict()` function

You can also create a dictionary with dict():

person = dict(first_name="John", last_name="Doe", age=30)

Notice:

  • Keys become strings automatically ("first_name", "last_name", "age").
  • You don’t use quotes around the keys in this syntax.

Accessing Values

You get a value from a dictionary by using its key in square brackets:

person = {
    "first_name": "John",
    "last_name": "Doe",
    "age": 30
}
print(person["first_name"])  # John
print(person["age"])         # 30

If you use a key that does not exist, Python raises a KeyError:

print(person["height"])  # KeyError: 'height'

Using `get()` to avoid errors

The method get() lets you ask for a key safely:

print(person.get("age"))        # 30
print(person.get("height"))     # None (no error)
print(person.get("height", 0))  # 0 (default value)

get(key, default) returns:

  • The value if key exists
  • Otherwise the default you provide (or None if you don’t provide one)

Adding and Changing Entries

You add a new key–value pair or change an existing one using assignment:

Adding a new key–value pair

person = {"name": "Alice"}
person["age"] = 25  # add a new key 'age'
print(person)       # {'name': 'Alice', 'age': 25}

Changing an existing value

person["age"] = 26  # change existing value
print(person)       # {'name': 'Alice', 'age': 26}

Updating multiple keys with `update()`

The update() method lets you add or modify several keys at once:

person = {"name": "Bob", "age": 20}
person.update({"age": 21, "city": "London"})
print(person)
# {'name': 'Bob', 'age': 21, 'city': 'London'}

You can also use keyword arguments with update():

person.update(age=22, country="UK")

Removing Entries

Dictionaries provide several ways to remove items.

Using `del`

del deletes a specific key (and its value):

person = {"name": "Alice", "age": 26, "city": "Paris"}
del person["city"]
print(person)  # {'name': 'Alice', 'age': 26}

Using del with a missing key will cause a KeyError.

Using `pop()`

pop(key) removes the key and returns its value:

age = person.pop("age")
print(age)     # 26
print(person)  # {'name': 'Alice'}

You can provide a default value to avoid errors if the key is missing:

result = person.pop("height", None)
print(result)  # None (no error)

Using `popitem()`

popitem() removes and returns the last added key–value pair (in modern Python versions):

data = {"a": 1, "b": 2, "c": 3}
key, value = data.popitem()
print(key, value)  # 'c', 3 (typically)

This is mostly useful when you treat the dictionary like a stack of items.

Clearing all entries

To remove everything from a dictionary:

person.clear()
print(person)  # {}

Keys, Values, and Items

Dictionaries have helpful methods to look at their contents.

`keys()`

Returns a “view” of all keys:

person = {"name": "Alice", "age": 26, "city": "Paris"}
print(person.keys())  # dict_keys(['name', 'age', 'city'])

`values()`

Returns a view of all values:

print(person.values())  # dict_values(['Alice', 26, 'Paris'])

`items()`

Returns a view of all key–value pairs as tuples:

print(person.items())
# dict_items([('name', 'Alice'), ('age', 26), ('city', 'Paris')])

You can turn these views into lists if needed:

keys_list = list(person.keys())
values_list = list(person.values())
items_list = list(person.items())

Looping Over Dictionaries

Dictionaries are often used together with for loops.

Looping over keys (default)

When you loop directly over a dictionary, you get its keys:

person = {"name": "Alice", "age": 26, "city": "Paris"}
for key in person:
    print(key, "->", person[key])

This is the same as:

for key in person.keys():
    print(key, "->", person[key])

Looping over values

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

Looping over key–value pairs with `items()`

This is often the most convenient way:

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

This uses tuple unpacking: each item is a tuple (key, value), and for key, value in ... splits it into two variables.

Checking for Keys

To check if a key exists in a dictionary, use the in keyword:

person = {"name": "Alice", "age": 26}
print("name" in person)   # True
print("height" in person) # False

This checks keys, not values. To check for a value in values():

print(26 in person.values())  # True

Valid Keys (and Common Pitfall)

Not everything can be used as a dictionary key. Keys must be:

  • Immutable (cannot change after creation)
  • Examples of valid keys:
    • str (string)
    • int, float
    • tuple (if it only contains immutable items)
  • Examples of invalid keys:
    • list
    • dict
    • set

Using a list as a key will raise a TypeError:

bad_dict = {}
bad_dict[[1, 2, 3]] = "hello"  # TypeError: unhashable type: 'list'

Strings are a very common choice for keys in beginner programs.

Nested Dictionaries (Dictionaries Inside Dictionaries)

Dictionaries can contain other dictionaries as values. This is useful for representing structured data.

Example: students by ID

students = {
    "s001": {"name": "Alice", "age": 20},
    "s002": {"name": "Bob", "age": 22},
}
print(students["s001"]["name"])  # Alice

Here:

  • students is a dictionary
  • Each value (like {"name": "Alice", "age": 20}) is another dictionary

You can modify nested values by chaining square brackets:

students["s001"]["age"] = 21

Example: inventory of items

inventory = {
    "apple": {"price": 0.5, "quantity": 10},
    "banana": {"price": 0.3, "quantity": 5},
}
# Access banana price
print(inventory["banana"]["price"])  # 0.3
# Increase apple quantity
inventory["apple"]["quantity"] += 5

Common Dictionary Methods (Beginner‑Friendly)

Here are some useful methods again, summarized with simple examples:

user = {"name": "Alice", "age": 25}
# get()
print(user.get("age", 0))      # 25
print(user.get("height", 0))   # 0
# update()
user.update({"city": "Paris"})
user.update(age=26)
# pop()
age = user.pop("age", None)    # removes 'age' and returns 26
# keys(), values(), items()
print(list(user.keys()))
print(list(user.values()))
print(list(user.items()))

Typical Use Cases for Dictionaries

Dictionaries are particularly handy when:

  • You want to look up something quickly by a label:
    • country → capital city
    • username → user information
  • You want to store settings or configuration options:
    • "theme": "dark", "language": "en", "volume": 70
  • You want to count things (e.g., word frequencies):
    • word → number of times it appears
  • You want to represent records (like a row in a table):
    • "title": "Inception", "year": 2010, "rating": 8.8

Small Practice Ideas

Here are some simple tasks you can try (you don’t need to write full programs yet—just experiment in the Python shell or a script):

  1. Create a dictionary capitals that maps a few countries to their capital cities.
    • Look up the capital of one country.
    • Add a new country and its capital.
  2. Make a prices dictionary for 3 products.
    • Change the price of one product.
    • Loop over the dictionary and print: "Product: X, Price: Y".
  3. Create a contact dictionary with keys "name", "phone", "email".
    • Use get() to safely read a "address" key, providing a default like "Unknown".

These small experiments will help you feel comfortable with creating, reading, updating, and looping over dictionaries.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms