2 2 6 Dictionaries Explained
Key Concepts
Dictionaries in Python are a collection of key-value pairs. They are unordered, mutable, and indexed by keys. The key concepts related to dictionaries include:
- Creating Dictionaries
- Accessing Values
- Adding and Modifying Entries
- Removing Entries
- Dictionary Methods
1. Creating Dictionaries
Dictionaries are created using curly braces {} or the dict() constructor. Each key-value pair is separated by a colon :, and pairs are separated by commas.
Example:
my_dict = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
2. Accessing Values
Values in a dictionary can be accessed using their keys. If the key does not exist, a KeyError is raised. You can also use the get() method, which returns None if the key is not found.
Example:
name = my_dict['name'] # Accessing value using key
age = my_dict.get('age') # Accessing value using get() method
3. Adding and Modifying Entries
You can add new key-value pairs to a dictionary by assigning a value to a new key. Existing keys can be modified by reassigning their values.
Example:
my_dict['email'] = 'alice@example.com' # Adding a new key-value pair
my_dict['age'] = 26 # Modifying an existing key's value
4. Removing Entries
Entries can be removed from a dictionary using the del statement or the pop() method. The pop() method removes the key-value pair and returns the value.
Example:
del my_dict['city'] # Removing an entry using del
email = my_dict.pop('email') # Removing an entry using pop()
5. Dictionary Methods
Python provides several built-in methods for dictionaries, such as keys(), values(), and items(). These methods return views of the dictionary's keys, values, and key-value pairs, respectively.
Example:
keys = my_dict.keys() # Returns a view of the dictionary's keys
values = my_dict.values() # Returns a view of the dictionary's values
items = my_dict.items() # Returns a view of the dictionary's key-value pairs
Understanding dictionaries is crucial for managing and organizing data efficiently in Python. By mastering these concepts, you can create, manipulate, and access data in a flexible and powerful way.