Week 7: Expanding Your Data Structure Toolkit

Explore tuples and dictionaries to organize data in powerful ways.

Explore Chapter 7

Chapter 7: More Ways to Structure Data

Tuples: Immutable Sequences.

Tuples are similar to lists in that they are ordered collections of items. However, a key difference is that tuples are immutable, meaning that once you create a tuple, you cannot change its contents (add, remove, or modify elements).

Creating Tuples

You create a tuple by enclosing a comma-separated sequence of items in parentheses `()`.

# Empty tuple
empty_tuple = ()

# Tuple of integers
numbers = (1, 2, 3, 4, 5)

# Tuple of strings
colors = ("red", "green", "blue")

# Tuple of mixed data types
mixed_tuple = (1, "hello", 3.14, True)

# Tuple with a single element (note the trailing comma!)
single_element_tuple = (5,)

The trailing comma is crucial for tuples with a single element. Without it, Python will interpret the expression as a simple value, not a tuple.

Accessing Elements

You access elements in a tuple using their index, just like with lists.

fruits = ("apple", "banana", "cherry")
first_fruit = fruits[0]   # "apple"
second_fruit = fruits[1]  # "banana"
last_fruit = fruits[-1]    # "cherry"

Tuple Immutability

Because tuples are immutable, you cannot do the following:

my_tuple = (1, 2, 3)
# my_tuple[0] = 10  # This will raise a TypeError!
# my_tuple.append(4) # This will also raise an AttributeError!
# del my_tuple[1]    # And this will raise a TypeError!

Why Use Tuples?

Tuples are useful when you want to ensure that data remains constant throughout the program. They are often used for representing fixed collections of related items, such as coordinates (x, y), RGB colors (r, g, b), or database records.

Dictionaries: Key-Value Pairs.

Dictionaries are another fundamental and powerful data structure in Python. Unlike lists and tuples, which are indexed by a range of numbers, dictionaries are indexed by keys. Dictionaries are also known as associative arrays or hash tables in other programming languages.

Creating Dictionaries

You create a dictionary by enclosing a comma-separated sequence of key-value pairs in curly braces `{}`. Each key-value pair is separated by a colon `:`.

# Empty dictionary
empty_dict = {}

# Dictionary mapping names to ages
ages = {"Alice": 30, "Bob": 25, "Charlie": 40}

# Dictionary mapping words to their definitions
definitions = {
    "Python": "A high-level programming language",
    "List": "An ordered collection of items",
    "Dictionary": "A collection of key-value pairs"
}
  • Keys must be immutable objects (like strings, numbers, or tuples).
  • Values can be of any data type (including lists, tuples, or even other dictionaries).
  • Dictionaries are unordered (as of Python 3.7, dictionaries maintain insertion order, but relying on this for older versions is not recommended).
  • Keys must be unique within a dictionary.

Accessing Values

You access the value associated with a key using square brackets `[]` with the key inside.

ages = {"Alice": 30, "Bob": 25, "Charlie": 40}
alice_age = ages["Alice"]  # 30
bob_age = ages["Bob"]    # 25

If you try to access a key that doesn't exist in the dictionary, you'll get a `KeyError`.

Modifying Dictionaries

Dictionaries are mutable, so you can change their contents.

  • Adding a new key-value pair:
    ages["David"] = 35
  • Modifying an existing value:
    ages["Alice"] = 31
  • Removing a key-value pair:
    del ages["Bob"]

Common Dictionary Methods.

Dictionaries provide several useful methods for working with their data.

  • `keys()`: Returns a view object that contains all the keys in the dictionary.
    ages = {"Alice": 30, "Bob": 25, "Charlie": 40}
    all_keys = ages.keys()  # Returns a view object, not a list in Python 3
  • `values()`: Returns a view object that contains all the values in the dictionary.
    all_values = ages.values() # Returns a view object
  • `items()`: Returns a view object that contains all the key-value pairs in the dictionary as tuples.
    all_items = ages.items() # Returns a view object of (key, value) tuples
  • `get(key, default)`: Returns the value associated with the `key`. If the `key` is not found, it returns the `default` value (or `None` if no `default` is provided). This is a safer way to access values than using `[]` as it avoids `KeyError`s.
    alice_age = ages.get("Alice")  # 30
    david_age = ages.get("David", "Not found") # "Not found"
  • `pop(key, default)`: Removes the key and returns the corresponding value. If the key is not found, it returns the `default` value (or raises a `KeyError` if no `default` is provided).
    removed_age = ages.pop("Bob") # 25
    # ages.pop("David") # Raises KeyError if "David" is not a key
    ages.pop("David", "Not found") # Returns "Not found" if "David" is not a key
  • `popitem()`: Removes and returns an arbitrary (key, value) pair. (The last-inserted item is removed in versions before Python 3.7).
    last_item = ages.popitem()
  • `clear()`: Removes all items from the dictionary.
    ages.clear() # ages is now {}
  • `copy()`: Returns a shallow copy of the dictionary.
    ages_copy = ages.copy()
  • `update(other_dict)`: Updates the dictionary with the key-value pairs from `other_dict`. Existing keys are overwritten, and new keys are added.
    more_ages = {"Eve": 28, "Frank": 33}
    ages.update(more_ages)
Syllabus