What is a Python Dictionary?
A Python dictionary is an unordered, mutable collection of items where each item is a key-value pair. You define a dictionary using curly braces, like {'name': 'John', 'age': 30}
.
Why Python Dictionaries are Important
Dictionaries are great for organizing data. They let you access information by a unique key, not by an index number. This makes your code clear and efficient. You use dictionaries to store user profiles, configuration settings, or any data with unique identifiers.
3 Steps to Use Python Dictionaries
Here’s how you can start using dictionaries in Python.
Step 1: Create a Dictionary
You create a dictionary by putting key-value pairs inside curly braces. Each key connects to a value. You separate keys from values with a colon (:). You separate each key-value pair with a comma (,).
Here’s how you create a simple dictionary:
# Create a dictionary named 'user_profile'
user_profile = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
print(user_profile)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
You can also create an empty dictionary and add items later:
# Create an empty dictionary
empty_dict = {}
# Add a key-value pair
empty_dict['fruit'] = 'apple'
empty_dict['color'] = 'red'
print(empty_dict)
# Output: {'fruit': 'apple', 'color': 'red'}
Step 2: Access Dictionary Values
You access values in a dictionary using their keys. You put the key inside square brackets after the dictionary’s name.
# Access values from 'user_profile'
name = user_profile['name']
age = user_profile['age']
print(f"Name: {name}, Age: {age}")
# Output: Name: Alice, Age: 25
If a key does not exist, Python will show a KeyError
. You can use the get()
method to avoid this. The get()
method returns None
or a default value if the key is not found.
# Using get() to access values
country = user_profile.get('country')
print(f"Country: {country}")
# Output: Country: None
# Using get() with a default value
occupation = user_profile.get('occupation', 'Unemployed')
print(f"Occupation: {occupation}")
# Output: Occupation: Unemployed
Step 3: Modify and Delete Dictionary Items
Dictionaries are mutable. This means you can change, add, or remove key-value pairs after you create them.
Add or Update Items
To add a new item, assign a value to a new key. If the key already exists, this will update its value.
# Add a new item to 'user_profile'
user_profile['email'] = 'alice@example.com'
print(user_profile)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'email': 'alice@example.com'}
# Update an existing item
user_profile['age'] = 26
print(user_profile)
# Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}
Delete Items
You use the del
keyword to remove a key-value pair. You can also use pop()
to remove an item and get its value back. The clear()
method empties the dictionary.
# Delete an item using del
del user_profile['city']
print(user_profile)
# Output: {'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}
# Remove an item and get its value using pop()
removed_email = user_profile.pop('email')
print(f"Removed Email: {removed_email}")
print(user_profile)
# Output: Removed Email: alice@example.com
# Output: {'name': 'Alice', 'age': 26}
# Clear all items from the dictionary
user_profile.clear()
print(user_profile)
# Output: {}
In this course, you will learn the fundamentals of Python: from basic syntax to mastering data structures, loops, and functions. You will also explore OOP concepts and objects to build robust programs.
Dictionary Methods You Can Use
Python dictionaries have many built-in methods. These methods help you work with dictionary items.
- keys(): This method returns a view of all keys in the dictionary.
- values(): This method returns a view of all values in the dictionary.
- items(): This method returns a view of all key-value pairs (as tuples) in the dictionary.
my_dict = {
'product': 'laptop',
'price': 1200,
'quantity': 10
}
# Get all keys
keys = my_dict.keys()
print(f"Keys: {list(keys)}") # Output: Keys: ['product', 'price', 'quantity']
# Get all values
values = my_dict.values()
print(f"Values: {list(values)}") # Output: Values: ['laptop', 1200, 10]
# Get all items
items = my_dict.items()
print(f"Items: {list(items)}") # Output: Items: [('product', 'laptop'), ('price', 1200), ('quantity', 10)]
You can use these methods to loop through a dictionary.
# Loop through keys
print("Looping through keys:")
for key in my_dict.keys():
print(key)
# Loop through values
print("\nLooping through values:")
for value in my_dict.values():
print(value)
# Loop through items
print("\nLooping through items:")
for key, value in my_dict.items():
print(f"{key}: {value}")
Check for Key Existence
You can check if a key exists in a dictionary using the in
operator. This helps you avoid KeyError
before trying to access a value.
user_data = {'name': 'Bob', 'age': 40}
# Check if 'name' key exists
if 'name' in user_data:
print("Name exists.")
else:
print("Name does not exist.")
# Output: Name exists.
# Check if 'email' key exists
if 'email' in user_data:
print("Email exists.")
else:
print("Email does not exist.")
# Output: Email does not exist.
Copying Dictionaries
When you copy a dictionary, you need to be careful. A simple assignment like new_dict = old_dict
creates a reference, not a true copy. Changes to new_dict
will also affect old_dict
.
To create a real copy, use the copy()
method or the dict()
constructor.
Shallow Copy
A shallow copy creates a new dictionary. It copies the references of the nested objects. If your dictionary contains lists or other dictionaries, changing those nested objects in the copy will affect the original.
original_dict = {'a': 1, 'b': [2, 3]}
shallow_copy_dict = original_dict.copy()
print(f"Original: {original_dict}")
print(f"Shallow Copy: {shallow_copy_dict}")
# Output:
# Original: {'a': 1, 'b': [2, 3]}
# Shallow Copy: {'a': 1, 'b': [2, 3]}
# Modify the shallow copy
shallow_copy_dict['a'] = 100
shallow_copy_dict['b'].append(4) # This modifies the list in both dictionaries
print(f"Original after change: {original_dict}")
print(f"Shallow Copy after change: {shallow_copy_dict}")
# Output:
# Original after change: {'a': 1, 'b': [2, 3, 4]}
# Shallow Copy after change: {'a': 100, 'b': [2, 3, 4]}
Deep Copy
A deep copy creates a completely independent copy, including all nested objects. Use the deepcopy()
function from the copy
module for this.
import copy
original_dict_nested = {'data': {'value': 10}}
deep_copy_dict = copy.deepcopy(original_dict_nested)
print(f"Original: {original_dict_nested}")
print(f"Deep Copy: {deep_copy_dict}")
# Output:
# Original: {'data': {'value': 10}}
# Deep Copy: {'data': {'value': 10}}
# Modify the deep copy
deep_copy_dict['data']['value'] = 20
print(f"Original after change: {original_dict_nested}")
print(f"Deep Copy after change: {deep_copy_dict}")
# Output:
# Original after change: {'data': {'value': 10}}
# Deep Copy after change: {'data': {'value': 20}}
Dictionary Comprehension
You can create dictionaries using dictionary comprehension. This works like list comprehension but for dictionaries. It helps you build dictionaries from iterables, or filter and transform existing ones.
# Create a dictionary from a list of numbers, squaring each number
numbers = [1, 2, 3, 4, 5]
squared_dict = {num: num**2 for num in numbers}
print(f"Squared Dictionary: {squared_dict}")
# Output: Squared Dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Create a dictionary from two lists (keys and values)
keys = ['apple', 'banana', 'cherry']
values = [10, 20, 30]
fruit_prices = {key: value for key, value in zip(keys, values)}
print(f"Fruit Prices: {fruit_prices}")
# Output: Fruit Prices: {'apple': 10, 'banana': 20, 'cherry': 30}
# Filter items from an existing dictionary
original = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
even_values = {key: value for key, value in original.items() if value % 2 == 0}
print(f"Even Values Dictionary: {even_values}")
# Output: Even Values Dictionary: {'b': 2, 'd': 4}
Best Practices for Python Dictionaries
- Choose Meaningful Keys: Use descriptive keys. This makes your code easier to read and understand.
- Use get() for Safe Access: Use
get()
to preventKeyError
when you are not sure if a key exists. - Avoid Mutable Keys: Dictionary keys must be immutable (e.g., strings, numbers, tuples). You cannot use lists or other dictionaries as keys.