Python dictionaries are a versatile and powerful data structure that allows you to store key-value pairs. They are commonly used for mapping and storing data in a way that allows for fast retrieval. This guide will cover the basics of Python dictionaries, CRUD (Create, Read, Update, Delete) operations, looping through dictionaries, methods, built-in functions, and more.
Creating Dictionaries
Dictionaries in Python can be created using curly braces {}
with key-value pairs or the dict()
constructor.
# Creating a dictionary with initial key-value pairs
person = {"name": "Alice", "age": 25, "profession": "Engineer"}
# Creating an empty dictionary
empty_dict = {}
# Using the dict() constructor
person = dict(name="Alice", age=25, profession="Engineer")
CRUD Operations
Create
You can create a dictionary by simply assigning key-value pairs to a variable.
# Creating a dictionary with initial key-value pairs
person = {"name": "Alice", "age": 25, "profession": "Engineer"}
Read
You can access values in a dictionary using keys.
# Accessing values by key
name = person["name"] # Output: "Alice"
age = person["age"] # Output: 25
Update
Dictionaries are mutable, meaning you can change their key-value pairs.
# Changing a value by key
person["age"] = 26 # person is now {"name": "Alice", "age": 26, "profession": "Engineer"}
# Adding a new key-value pair
person["city"] = "New York" # person is now {"name": "Alice", "age": 26, "profession": "Engineer", "city": "New York"}
Delete
You can remove key-value pairs from a dictionary using various methods.
# Removing a key-value pair by key
del person["profession"] # person is now {"name": "Alice", "age": 26, "city": "New York"}
# Removing a key-value pair and returning its value
age = person.pop("age") # Output: 26, person is now {"name": "Alice", "city": "New York"}
# Clearing all key-value pairs from the dictionary
person.clear() # person is now {}
Looping Through Dictionaries
You can loop through the keys, values, or key-value pairs of a dictionary using a for
loop.
person = {"name": "Alice", "age": 25, "profession": "Engineer"}
# Looping through keys
for key in person:
print(key)
# Looping through values
for value in person.values():
print(value)
# Looping through key-value pairs
for key, value in person.items():
print(f"Key: {key}, Value: {value}")
Dictionary Methods
Dictionaries come with a variety of built-in methods to perform common operations.
Method | Description | Example Code |
---|---|---|
clear() | Removes all key-value pairs from the dictionary. | person.clear() |
copy() | Returns a shallow copy of the dictionary. | person_copy = person.copy() |
fromkeys() | Creates a new dictionary with keys from an iterable and values set to a value. | new_dict = dict.fromkeys(["name", "age"], None) |
get() | Returns the value for a key if it exists, else returns a default value. | age = person.get("age", 0) |
items() | Returns a view object of the dictionary’s key-value pairs. | items = person.items() |
keys() | Returns a view object of the dictionary’s keys. | keys = person.keys() |
pop() | Removes and returns the value for a key if it exists, else raises a KeyError. | age = person.pop("age") |
popitem() | Removes and returns the last inserted key-value pair. | last_item = person.popitem() |
setdefault() | Returns the value for a key if it exists, else inserts the key with a default value. | age = person.setdefault("age", 0) |
update() | Updates the dictionary with key-value pairs from another dictionary or iterable. | person.update({"city": "New York"}) |
values() | Returns a view object of the dictionary’s values. | values = person.values() |
Examples
person = {"name": "Alice", "age": 25, "profession": "Engineer"}
# clear()
person.clear() # person is now {}
# copy()
person_copy = person.copy()
# fromkeys()
new_dict = dict.fromkeys(["name", "age"], None) # new_dict is {"name": None, "age": None}
# get()
age = person.get("age", 0) # Output: 25
# items()
items = person.items() # Output: dict_items([('name', 'Alice'), ('age', 25), ('profession', 'Engineer')])
# keys()
keys = person.keys() # Output: dict_keys(['name', 'age', 'profession'])
# pop()
age = person.pop("age") # Output: 25, person is now {"name": "Alice", "profession": "Engineer"}
# popitem()
last_item = person.popitem() # Output: ('profession', 'Engineer'), person is now {"name": "Alice"}
# setdefault()
age = person.setdefault("age", 0) # Output: 0, person is now {"name": "Alice", "age": 0}
# update()
person.update({"city": "New York"}) # person is now {"name": "Alice", "age": 0, "city": "New York"}
# values()
values = person.values() # Output: dict_values(['Alice', 0, 'New York'])
Built-in Functions for Dictionaries
Python provides several built-in functions that work with dictionaries:
Function | Description | Example Code |
---|---|---|
len() | Returns the number of key-value pairs in a dictionary. | len(person) |
max() | Returns the largest key in the dictionary. | max(person) |
min() | Returns the smallest key in the dictionary. | min(person) |
sorted() | Returns a new sorted list of the dictionary’s keys. | sorted(person) |
all() | Returns True if all keys in the dictionary are true. | all(person) |
any() | Returns True if any key in the dictionary is true. | any(person) |
enumerate() | Returns an enumerate object. It contains the index and key of all the items of dictionary as a pair. | enumerate(person) |
Examples
person = {"name": "Alice", "age": 25, "profession": "Engineer"}
# len()
print(len(person)) # Output: 3
# max()
print(max(person)) # Output: "profession"
# min()
print(min(person)) # Output: "age"
# sorted()
print(sorted(person)) # Output: ["age", "name", "profession"]
# all()
print(all(person)) # Output: True
# any()
print(any(person)) # Output: True
# enumerate()
for index, key in enumerate(person):
print(f"Index: {index}, Key: {key}")
When to Use Dictionaries
Use Cases
- Mapping Data: Use dictionaries when you need to map keys to values, such as storing user information or configuration settings.
- Fast Lookups: Dictionaries provide fast lookups for keys, making them ideal for scenarios where quick access to data is required.
- Dynamic Data: Dictionaries are suitable for storing dynamic data that may change over time, such as caching results or tracking state.
When Not to Use Dictionaries
- Ordered Collections: If you need to maintain the order of elements, consider using a list or an
OrderedDict
instead of a dictionary. - Unique Elements: If you need a collection of unique elements without key-value pairs, consider using a set instead of a dictionary.
- Fixed-Size Collections: If you need a fixed-size collection, consider using a tuple instead of a dictionary.
Scenario for Use Cases
Example 1: Mapping User Information
user = {"username": "alice123", "email": "alice@example.com", "age": 25}
Example 2: Configuration Settings
config = {"host": "localhost", "port": 8080, "debug": True}
Example 3: Caching Results
cache = {}
def get_data(key):
if key in cache:
return cache[key]
else:
data = fetch_data_from_source(key)
cache[key] = data
return data
Professional Tips
- Use Dictionary Comprehensions: Dictionary comprehensions provide a concise way to create dictionaries. They are often more readable and efficient than traditional loops.
- Avoid Modifying Dictionaries While Iterating: Modifying a dictionary while iterating over it can lead to unexpected behavior. Instead, create a new dictionary or use dictionary comprehensions.
- python # Correct way to filter a dictionary filtered_dict = {k: v for k, v in person.items() if v != “Engineer”}
- Leverage Built-in Functions: Python provides many built-in functions like
len()
,max()
,min()
, andsorted()
that work with dictionaries. Use them to write more concise and readable code.- python total_keys = len(person)
Conclusion
Python dictionaries are a powerful and flexible data structure that allows you to store and manipulate key-value pairs. By understanding the various methods and operations available for dictionaries, you can write more efficient and effective Python code. This guide covered the basics of creating dictionaries, performing CRUD operations, looping through dictionaries, dictionary methods, built-in functions, and additional tips. Happy coding!