Dictionaries are one of the most versatile data structures in Python. They allow you to store data in a way that is easy to retrieve, modify, and manage. At the core of a dictionary are key-value pairs, which act as an efficient way to link related data.
What is a Dictionary?
A dictionary in Python is an unordered collection of items. Each item is stored as a pair of a key and its corresponding value. Each key must be unique within a dictionary, while multiple keys can point to the same value, allowing for a flexible structure that represents real-world data better than traditional lists or arrays.
Creating a Dictionary
To create a dictionary, you can use curly braces {}
or the dict()
constructor. Here’s how you can do both:
# Using curly braces my_dict = { "name": "Alice", "age": 30, "city": "London" } # Using the dict() constructor my_dict = dict(name="Alice", age=30, city="London")
In both cases, we end up with a dictionary named my_dict
containing three key-value pairs.
Accessing Values
You can access the value associated with a key by using square brackets []
. If the key exists, it will return the value; if not, you'll get a KeyError
. For example:
print(my_dict["name"]) # Output: Alice print(my_dict["age"]) # Output: 30
Modifying Values
Dictionaries allow for easy updates. You can change an existing value by assigning a new value to its key:
my_dict["age"] = 31 print(my_dict["age"]) # Output: 31
You can also add new key-value pairs:
my_dict["occupation"] = "Engineer" print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'London', 'occupation': 'Engineer'}
Removing Key-Value Pairs
If you want to remove a specific key-value pair from a dictionary, you can use the del
keyword or the pop()
method. Here’s how both are used:
del my_dict["city"] # Removes the key 'city' print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'occupation': 'Engineer'} # Alternatively using pop() occupation = my_dict.pop("occupation") print(occupation) # Output: Engineer print(my_dict) # Output: {'name': 'Alice', 'age': 31}
Iterating Through a Dictionary
You can easily iterate over keys, values, or both in a dictionary. Here’s how to do that:
# Iterating through keys for key in my_dict: print(key) # Iterating through values for value in my_dict.values(): print(value) # Iterating through key-value pairs for key, value in my_dict.items(): print(f"{key}: {value}")
Nested Dictionaries
Dictionaries can also be nested, which means you can have a dictionary as a value for a key. This allows for more complex data structures. Here’s an example:
people = { "Alice": { "age": 30, "city": "London" }, "Bob": { "age": 25, "city": "New York" } } print(people["Alice"]["city"]) # Output: London
Summary of Key Features
To wrap up the capabilities of dictionaries, here's a brief summary of their key features:
- Dynamic Size: Unlike lists, the size of dictionaries can change based on additions and deletions of key-value pairs.
- Fast Access: Dictionaries are implemented using hash tables, which allow for average-case O(1) time complexity for lookups, inserts, and deletions.
- Flexible Data Types: Both keys and values can be of any immutable type. However, commonly used types for keys include strings, numbers, and tuples.
- Unordered Collections: As of Python 3.7, dictionaries maintain the insertion order, making them behave more like ordered collections.
Dictionaries are an essential part of Python programming. Whether you're working on data processing, managing configurations, or handling JSON data, dictionaries will often become your go-to structure for organizing data efficiently.