In Python, a dictionary is an unordered, mutable, and indexed collection of key-value pairs. Dictionaries are optimized for retrieving values when the corresponding key is known. The keys in a dictionary must be unique and immutable (such as strings, numbers, or tuples), while the values can be of any data type and can be duplicated.
1. Creating Dictionaries
Dictionaries are created by placing a comma-separated sequence of key-value pairs within curly braces {}
. Each key is followed by a colon :
and then the value.
# Creating an empty dictionary
empty_dict = {}
# Creating a dictionary with some key-value pairs
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Creating a dictionary using the dict() function
another_dict = dict(name="Bob", age=30, city="Los Angeles")
2. Accessing Dictionary Elements
You can access the values in a dictionary by referring to their keys inside square brackets []
.
print(my_dict["name"]) # Output: Alice
print(my_dict["age"]) # Output: 25
-
- Using the
get()
method: This method is safer than direct access because it does not raise an error if the key is not found; instead, it returnsNone
or a specified default value.
- Using the
print(my_dict.get("city")) # Output: New York
print(my_dict.get("country", "USA")) # Output: USA (default value)
3. Adding and Modifying Dictionary Elements
You can add new key-value pairs or modify existing ones by assigning a value to a key.
# Adding a new key-value pair
my_dict["email"] = "alice@example.com"
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'email': 'alice@example.com'}
# Modifying an existing value
my_dict["age"] = 26
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}
4. Removing Elements from a Dictionary
Dictionaries support several methods for removing elements.
pop(key)
: Removes the element with the specified key and returns its value. Raises aKeyError
if the key is not found.
age = my_dict.pop("age")
print(age) # Output: 26
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York', 'email': 'alice@example.com'}
popitem()
: Removes and returns the last inserted key-value pair as a tuple. In Python 3.7 and later, dictionaries maintain the insertion order.
last_item = my_dict.popitem()
print(last_item) # Output: ('email', 'alice@example.com')
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}
del
: Deletes the key-value pair associated with the specified key. You can also usedel
to delete the entire dictionary.
del my_dict["city"]
print(my_dict) # Output: {'name': 'Alice'}
# Deleting the entire dictionary
del my_dict
# print(my_dict) # Uncommenting this line will raise a NameError since my_dict no longer exists
clear()
: Removes all elements from the dictionary.
my_dict = {"name": "Alice", "age": 26, "city": "New York"}
my_dict.clear()
print(my_dict) # Output: {}
5. Dictionary Methods
Here are some commonly used dictionary methods:
keys()
: Returns a view object that displays a list of all the keys in the dictionary.
keys = my_dict.keys()
print(keys) # Output: dict_keys(['name', 'age', 'city'])
values()
: Returns a view object that displays a list of all the values in the dictionary.
values = my_dict.values()
print(values) # Output: dict_values(['Alice', 26, 'New York'])
items()
: Returns a view object that displays a list of all the key-value pairs in the dictionary as tuples.
items = my_dict.items()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 26), ('city', 'New York')])
update(other_dict)
: Updates the dictionary with the key-value pairs from another dictionary or from an iterable of key-value pairs.
my_dict.update({"email": "alice@example.com", "city": "San Francisco"})
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'San Francisco', 'email': 'alice@example.com'}
copy()
: Returns a shallow copy of the dictionary.
new_dict = my_dict.copy()
print(new_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'San Francisco', 'email': 'alice@example.com'}
6. Iterating Over a Dictionary
You can iterate over the keys, values, or key-value pairs of a dictionary using a for
loop.
# Iterating over keys
for key in my_dict:
print(key, my_dict[key])
# Iterating over values
for value in my_dict.values():
print(value)
# Iterating over key-value pairs
for key, value in my_dict.items():
print(key, value)
Output:
name Alice
age 26
city San Francisco
email alice@example.com
7. Dictionary Comprehensions
Dictionary comprehensions provide a concise way to create dictionaries. The syntax is similar to list comprehensions.
# Creating a dictionary with squares of numbers
squares = {x: x**2 for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
8. Nested Dictionaries
Dictionaries can contain other dictionaries, allowing you to create complex data structures.
nested_dict = {
"person1": {"name": "Alice", "age": 26},
"person2": {"name": "Bob", "age": 30}
}
print(nested_dict["person1"]["name"]) # Output: Alice
9. Dictionary vs. List
Feature | Dictionary | List |
---|---|---|
Access | Access elements via keys (unordered). | Access elements via index (ordered). |
Mutability | Mutable (can change values, add/remove keys). | Mutable (can change values, add/remove elements). |
Duplicates | Keys must be unique. | Allows duplicate elements. |
Performance | Faster lookups for large collections. | Slower lookups for large collections. |
Use Case | When you need to associate values with unique keys. | When you need an ordered collection of elements. |
10. Common Use Cases
- Storing Related Data: Dictionaries are ideal for storing related data where each value is associated with a unique key, such as an address book or configuration settings.
contact_info = {
"name": "Alice",
"phone": "123-456-7890",
"email": "alice@example.com"
}
- Counting Items: You can use a dictionary to count occurrences of elements.
text = "apple banana apple strawberry banana apple"
word_count = {}
for word in text.split():
word_count[word] = word_count.get(word, 0) + 1
print(word_count) # Output: {'apple': 3, 'banana': 2, 'strawberry': 1}
- Storing Configurations: Dictionaries are commonly used to store configuration settings.
config = {
"theme": "dark",
"language": "English",
"show_line_numbers": True
}
Dictionaries are a fundamental and versatile data structure in Python, allowing you to store and manage key-value pairs efficiently. They are especially useful when you need to retrieve data quickly based on a key, count occurrences of elements, or store structured data. Understanding how to work with dictionaries is crucial for effective Python programming, particularly when dealing with more complex data structures or when optimizing for performance.