Data Structures: Dictionaries
Introduction to Dictionaries
A dictionary in Python is a collection of key-value pairs. Each key must be unique and immutable, while the values can be of any type and can be changed.
Key Features of Dictionaries:
- Key-value pairs.
- Keys must be immutable (strings, numbers, tuples).
- Values can be of any type.
- No duplicate keys allowed.
- Unordered collection.
Creating Dictionaries
Dictionaries are created using curly braces {}
and key-value pairs separated by a colon :
. The key-value pairs are separated by commas ,
.
# Creating an empty dictionary
my_dict = {
"name": "Username",
"age": 20,
"city": "London"
}
Accessing Dictionary Elements
You can access dictionary elements using the key. If the key is not present in the dictionary, it will raise a KeyError
.
print(my_dict["name"]) # Output: Username
# Accessing using the get() method
print(my_dict.get("age")) # Output: 20
Modifying Dictionary Elements
You can modify dictionary elements by assigning a new value to the key.
my_dict["age"] = 21
print(my_dict) # Output: {'name': 'Username', 'age': 21, 'city': 'London'}
If a key is not found, get() returns None instead of raising an error.
print(my_dict.get("non_existent_key")) # Output: None
Adding and Removing Elements
You can add new key-value pairs to a dictionary by assigning a value to a new key.
my_dict["email"] = "[email protected]"
print(my_dict) # Output: {'name': 'Username', 'age': 21, 'city': 'London', 'email': '
You can remove key-value pairs from a dictionary using the del
keyword or the pop()
method.
pop(key)
: Removes the key and returns its value.del
: Deletes the key-value pair.popitem()
: Removes and returns the last inserted key-value pair.clear()
: Removes all items from the dictionary.
# Removing a key-value pair using the del keyword
del my_dict["city"]
print(my_dict) # Output: {'name': 'Username', 'age': 21, 'email': '[email protected]'
# Clearing all elements
my_dict.clear()
print(my_dict) # Output: {}
Dictionary Methods
Python provides several built-in methods to work with dictionaries:
Method | Description |
---|---|
get(key, default) | Returns the value for the key, or default if not found.. |
len() | Returns the number of key-value pairs in the dictionary. |
keys() | Returns a list of all keys in the dictionary. |
values() | Returns a list of all values in the dictionary. |
items() | Returns a list of key-value pairs as tuples. |
copy() | Returns a shallow copy of the dictionary. |
update() | Updates the dictionary with key-value pairs from another dictionary. |
fromkeys() | Creates a new dictionary with keys from a list and values set to a default value. |
pop(key, default) | Removes the key and returns its value, or default if the key is not found. |
popitem() | Removes and returns the last inserted key-value pair. |
clear() | Removes all items from the dictionary. |
setdefault(key, default) | Returns the value for the key, or sets it to default if the key is not found. |
# Getting all keys
print(my_dict.keys()) # Output: dict_keys(['name', 'email'])
# Getting all values
print(my_dict.values()) # Output: dict_values(['Username', '[email protected]'])
# Getting all items (key-value pairs)
print(my_dict.items()) # Output: dict_items([('name', 'Username'), ('email', '[email protected]')])
# Updating the dictionary with another dictionary
my_dict.update({"age": 26, "city": "San Francisco"})
print(my_dict) # Output: {'name': 'Username', 'email': '[email protected]', 'age': 26, 'city': 'San Francisco'}
Creating a new dictionary with keys from a list
# Creating a new dictionary with keys from a list
keys = ["name", "email", "age", "city"]
default_value = "N/A"
new_dict = dict.fromkeys(keys, default_value)
print(new_dict) # Output: {'name': 'N/A', 'email': 'N/A', 'age': 'N/A', 'city': 'N/A'}
You can loop through a dictionary using the for
loop to access the keys, values, or key-value pairs.
# Looping through keys
for key in my_dict:
print(key) # Output: 'name', 'email', 'age', 'city'
# Looping through values
for value in my_dict.values():
print(value) # Output: 'Username', '[email protected]', 26, 'San Francisco'
# Looping through key-value pairs
for key, value in my_dict.items():
print(f"{key}: {value}") # Output: 'name: Username', 'email: [email protected]', 'age: 26', 'city: San Francisco'
Dictionary Comprehensions
Dictionary comprehensions are similar to list comprehensions but create dictionaries instead of lists.
# Creating a dictionary with key-value pairs
squares = {x: x**2 for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Nested Dictionaries
You can create nested dictionaries by assigning a dictionary as a value to a key.
# Creating a nested dictionary
nested_dict = {
"user1": {
"name": "Username",
"age": 20,
"city": "London",
},
"user2": {
"name": "John",
"age": 25,
"city": "New York",
}
}
print(nested_dict["person1"]["name"]) # Output: Username
Real-World Use Cases of Dictionaries
Dictionaries are used in various applications, such as:
- Storing data mappings: For example, a contact list where the key is the person’s name and the value is their phone number or email.
- Counting occurrences: Using a dictionary to count how many times items appear in a list.
- Configuration settings: Storing configuration settings for an application.
- Caching: Storing the results of expensive calculations to avoid recomputing them.
items = ["apple", "banana", "apple", "orange", "banana", "apple"]
count_dict = {}
for item in items:
count_dict[item] = count_dict.get(item, 0) + 1
print(count_dict) # Output: {'apple': 3, 'banana': 2, 'orange': 1}
Conclusion
Dictionaries are one of the most powerful and flexible data structures in Python. With key-value pairs, they allow for efficient lookups, data mapping, and fast access to data. You can also perform various operations such as adding, modifying, or removing elements, and even nest dictionaries within one another for more complex structures.
This chapter covers everything you need to know about Python dictionaries, from basic operations to advanced techniques like dictionary comprehension and nested dictionaries.
Now that you have a good understanding of dictionaries, you can start using them in your Python programs to store and manage data efficiently.