Your First Steps in Python: A Beginner to Intermediate Guide

Dictionaries: Key-Value Pairs for Efficient Lookups

Section 5

Data Structures: Organizing Collections of Data

Your First Steps in Python: A Beginner to Intermediate GuideData Structures: Organizing Collections of Data

Dictionaries are one of Python's most powerful built-in data structures. Unlike lists or tuples where elements are accessed by their numerical index, dictionaries store data as key-value pairs. This means each piece of data is associated with a unique identifier, called a key, allowing for incredibly efficient retrieval and management of information.

Think of a real-world dictionary. You look up a word (the key) to find its definition (the value). Python dictionaries work in a very similar fashion. This key-value structure makes dictionaries ideal for situations where you need to quickly find information based on a specific label rather than its position.

Creating a dictionary is straightforward. You use curly braces {} and separate key-value pairs with commas. Each key is separated from its value by a colon :. Keys must be unique and immutable (like strings, numbers, or tuples), while values can be any Python object.

student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

Accessing values in a dictionary is done using the key within square brackets []. This is significantly more intuitive and often more efficient than iterating through a list to find a specific item.

print(student["name"])
print(student["age"])

If you try to access a key that doesn't exist, Python will raise a KeyError. To avoid this, you can use the .get() method, which allows you to provide a default value if the key is not found.

print(student.get("grade", "Not specified"))
チャプターへ戻る