In this lesson, we will explore Dictionaries, which are one of the most important and versatile data structures in Python. Dictionaries allow you to store key-value pairs, where each key is unique and maps to a specific value. Dictionaries are widely used to represent structured data like records, settings, or any data that needs to be quickly accessed using a specific identifier (the key).
By the end of this lesson, you will understand how to create dictionaries, access and modify values, and iterate over the elements within a dictionary.
1. Creating Dictionaries
A dictionary in Python is an unordered collection of items, where each item is a pair consisting of a key and a value. The keys are unique within a dictionary, and they are typically immutable types, such as strings or numbers. The values associated with the keys can be any data type, including lists, tuples, or even other dictionaries.
Syntax:
Example:
person = {“name”: “Alice”, “age”: 30, “city”: “New York”}
# A dictionary with mixed data types as values
car = {“make”: “Toyota”, “model”: “Corolla”, “year”: 2020, “colors”: [“red”, “blue”, “black”]}
# A dictionary with numerical keys
number_mapping = {1: “one”, 2: “two”, 3: “three”}
- Keysmust be immutable types like strings, numbers, or tuples. They cannot be lists or other dictionaries.
- Valuescan be of any data type, and they can be changed.
You can also create an empty dictionary using curly braces or the dict() constructor.
empty_dict = {}
# Creating an empty dictionary using dict()
empty_dict2 = dict()
2. Accessing and Modifying Dictionary Values
To access values in a dictionary, you use the key associated with the value you want to retrieve. You can use square brackets [] or the get() method.
Accessing Dictionary Values:
- Using square brackets ([]):
person = {“name”: “Alice”, “age”: 30, “city”: “New York”}
print(person[“name”]) # Output: Alice
- Using the get()method: The get() method returns the value for a specified key. If the key does not exist, it returns None (or a default value if provided).
print(person.get(“age”)) # Output: 30
print(person.get(“gender”, “Not specified”)) # Output: Not specified (default value)
Modifying Dictionary Values:
You can modify the value associated with an existing key by simply assigning a new value to that key.
print(person) # Output: {‘name’: ‘Alice’, ‘age’: 31, ‘city’: ‘New York’}
# Adding a new key-value pair
person[“email”] = “alice@example.com”
print(person) # Output: {‘name’: ‘Alice’, ‘age’: 31, ‘city’: ‘New York’, ’email’: ‘alice@example.com’}
- If the key exists, the value is updated.
- If the key does not exist, a new key-value pair is added to the dictionary.
Removing Items from a Dictionary:
You can remove items from a dictionary using the del statement, the pop() method, or the popitem() method.
- Using del: The delstatement deletes a key-value pair from the dictionary.
print(person) # Output: {‘name’: ‘Alice’, ‘age’: 31, ‘city’: ‘New York’}
- Using pop(): The pop()method removes and returns the value associated with the specified key.
age = person.pop(“age”) # Remove and return the value for the key ‘age’
print(age) # Output: 31
print(person) # Output: {‘name’: ‘Alice’, ‘city’: ‘New York’}
- Using popitem(): The popitem()method removes and returns a random key-value pair as a tuple.
item = person.popitem()
print(item) # Output: (‘city’, ‘New York’) (random key-value pair)
print(person) # Output: {‘name’: ‘Alice’}
3. Iterating Over Dictionaries
You can iterate over the keys, values, or key-value pairs of a dictionary using various methods.
Iterating Over Keys:
You can use a for loop to iterate over the keys of a dictionary.
# Iterating over keys
for key in person:
print(key) # Output: name, age, city (in any order, as dictionaries are unordered)
Alternatively, you can use the keys() method to explicitly get the keys.
print(key) # Output: name, age, city
Iterating Over Values:
To iterate over the values of a dictionary, use the values() method.
for value in person.values():
print(value) # Output: Alice, 30, New York
Iterating Over Key-Value Pairs:
To iterate over both keys and values simultaneously, you can use the items() method.
print(key, “:”, value) # Output: name: Alice, age: 30, city: New York
Using Dictionary Comprehensions:
You can use dictionary comprehensions to create or filter dictionaries in a concise manner.
# Creating a dictionary using comprehension
squared_numbers = {x: x**2 for x in range(5)}
print(squared_numbers) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Filtering a dictionary
filtered_dict = {key: value for key, value in person.items() if key != “city”}
print(filtered_dict) # Output: {‘name’: ‘Alice’, ‘age’: 30}
4. Common Dictionary Methods
Python provides several built-in methods for working with dictionaries. Here are some of the most commonly used methods:
- clear(): Removes all items from the dictionary.
person.clear()
print(person) # Output: {}
- copy(): Returns a shallow copy of the dictionary.
print(new_person) # Output: {‘name’: ‘Alice’, ‘age’: 30}
- get(key, default): Returns the value for the given key if it exists, otherwise returns the defaultvalue (if provided).
print(person.get(“address”, “Not found”)) # Output: Not found
- pop(key): Removes the specified key and returns its associated value.
print(address) # Output: No address found
- update(): Updates the dictionary with key-value pairs from another dictionary or iterable.
print(person) # Output: {‘name’: ‘Alice’, ‘age’: 30, ‘city’: ‘New York’, ‘address’: ‘123 Main St’, ‘phone’: ‘123-456-7890’}
5. When to Use Dictionaries
Dictionaries are best suited for situations where:
- You need fast access to values based on a unique key.
- You want to store related data as key-value pairs (e.g., names and ages, product IDs and prices, etc.).
- You need to manage settings, configurations, or user data that require flexible and fast lookups.
Dictionaries are often used in tasks such as:
- Storing data like user profiles, configuration settings, or state information.
- Representing real-world entities like products, employees, or students where the keys are identifiers (such as names, IDs, or product codes).
- Implementing caches, mappings, or dictionaries of variables that can be dynamically updated.
6. Conclusion
In this lesson, you have learned:
- How to createdictionaries and access their elements.
- How to modify, remove, and addkey-value pairs in dictionaries.
- The different ways to iterateover dictionaries, including iterating over keys, values, and key-value pairs.
- The common dictionary methods that allow you to manipulate data effectively.
Dictionaries are a fundamental and powerful data structure in Python, providing an efficient way to store, manage, and retrieve data. In the next lessons, we will continue exploring other data structures like sets and their applications.
Leave a Reply