Dictionaries are a fundamental data structure in Python, offering a powerful way to store and manage data in key-value pairs. This tutorial provides a comprehensive guide to working with Python dictionaries, covering creation, manipulation, and iteration.
Table of Contents
- Creating Dictionaries
- Accessing Elements
- Updating Dictionaries
- Deleting Elements
- Dictionary Methods
- Common Operations
- Iterating Through Dictionaries
- Built-in Functions and Dictionaries
1. Creating Dictionaries
Python dictionaries are defined using curly braces {}
, with key-value pairs separated by colons :
. Keys must be immutable (e.g., strings, numbers, tuples), while values can be of any data type.
# Creating a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Creating an empty dictionary
empty_dict = {}
print(empty_dict) # Output: {}
# Another way to create a dictionary using the dict() constructor
my_dict2 = dict(name="Bob", age=25, city="Los Angeles")
print(my_dict2) # Output: {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}
2. Accessing Elements
Elements are accessed using their keys. The get()
method provides a safer alternative, returning a default value if the key is not found, preventing KeyError
exceptions.
print(my_dict["name"]) # Output: Alice
print(my_dict.get("age")) # Output: 30
print(my_dict.get("country", "Unknown")) # Output: Unknown (key 'country' doesn't exist)
# print(my_dict["country"]) # This would raise a KeyError
3. Updating Dictionaries
Existing values can be updated, and new key-value pairs can be added.
my_dict["age"] = 31 # Update existing value
my_dict["country"] = "USA" # Add a new key-value pair
print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'country': 'USA'}
# Using the update() method to add multiple key-value pairs
my_dict.update({"city": "San Francisco", "occupation": "Engineer"})
print(my_dict)
4. Deleting Elements
Several methods facilitate element deletion:
del my_dict["city"] # Delete a key-value pair
print(my_dict)
my_dict.pop("age") # Removes and returns the value associated with the key
print(my_dict)
removed_item = my_dict.pop("occupation", "Not Found") # Returns default if key not found
print(removed_item)
print(my_dict)
my_dict.clear() # Removes all items
print(my_dict) # Output: {}
5. Dictionary Methods
Python dictionaries offer numerous built-in methods: keys()
, values()
, items()
, copy()
, clear()
, pop()
, popitem()
, setdefault()
, update()
. Consult the Python documentation for detailed explanations.
6. Common Operations
Check for key existence using the in
operator:
print("name" in my_dict) # Output: True (assuming my_dict is re-initialized)
print("country" in my_dict) # Output: False
Get the number of key-value pairs using len()
:
my_dict = {"a": 1, "b": 2, "c": 3}
print(len(my_dict)) # Output: 3
7. Iterating Through Dictionaries
Iterate through keys, values, or key-value pairs:
for key in my_dict:
print(key) # Iterates through keys
for value in my_dict.values():
print(value) # Iterates through values
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}") # Iterates through key-value pairs
8. Built-in Functions and Dictionaries
Functions like len()
, sorted()
, and all()
work with dictionaries. sorted()
sorts keys, and all()
checks if all values meet a condition.
This tutorial provides a solid foundation for working with Python dictionaries. For advanced features and use cases, refer to the official Python documentation. Consistent practice is key to mastering this essential data structure.