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"))Adding or modifying key-value pairs is as simple as assigning a value to a key. If the key already exists, its value will be updated; if it doesn't, a new pair will be created.
student["gpa"] = 3.8
student["age"] = 21