Creating and Using Dictionaries in Python
Dictionaries are one of the most powerful and versatile data structures in Python. They allow you to store key-value pairs, making it easy to organize and retrieve data efficiently.
What is a Dictionary?
A dictionary in Python is an unordered collection of items. Each item consists of a key and its corresponding value. Keys must be unique and immutable (like strings, numbers, or tuples), while values can be of any type.
Why Use Dictionaries?
- Fast Lookups: Accessing values by their keys is extremely efficient.
- Flexible Data Storage: You can store diverse types of data as values.
- Dynamic Updates: Easily add, modify, or remove key-value pairs.
Creating a Dictionary
To create a dictionary, use curly braces {}
and specify key-value pairs separated by commas. Here's an example:
# Creating a dictionary
person = {
'name': 'Alice',
'age': 25,
'is_student': True
}
print(person)
This creates a dictionary named person
with three key-value pairs.
Accessing and Modifying Data
You can access values using their keys or modify them as follows:
# Accessing a value
print(person['name']) # Output: Alice
# Modifying a value
person['age'] = 26
print(person['age']) # Output: 26
# Adding a new key-value pair
person['city'] = 'New York'
print(person)
Common Dictionary Methods
Dictionaries come with several built-in methods that simplify common tasks:
- keys(): Returns all the keys in the dictionary.
print(person.keys())
- values(): Returns all the values.
print(person.values())
- items(): Returns key-value pairs as tuples.
print(person.items())
- get(key, default): Retrieves the value for a given key, or returns a default if the key doesn't exist.
print(person.get('height', 'Not specified'))
Real-World Applications
Dictionaries are widely used in various scenarios, such as:
- Storing configuration settings.
- Counting occurrences of elements (e.g., word frequency).
- Mapping relationships between entities (e.g., adjacency lists in graphs).
With these foundational skills, you're now ready to leverage dictionaries effectively in your Python projects!