Dictionaries in Python
Dictionaries are mutable, unordered collections of key-value pairs in Python. They are defined using curly braces and allow for fast access to values based on their corresponding keys.
Creating a Dictionary
You can create a dictionary by enclosing key-value pairs in curly braces. Each key is separated from its value by a colon, and pairs are separated by commas.
Example of Creating a Dictionary
# Creating a dictionary
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print("Dictionary created:", my_dict)
Output
Accessing Values in a Dictionary
You can access values in a dictionary by using the key in square brackets. If the key does not exist, a KeyError
will be raised.
Example of Accessing Values
# Accessing values in a dictionary
name = my_dict["name"]
age = my_dict["age"]
print("Name:", name)
print("Age:", age)
Output
Age: 30
Adding and Updating Values in a Dictionary
You can add a new key-value pair to a dictionary by assigning a value to a new key. To update an existing value, simply assign a new value to the existing key.
Example of Adding and Updating Values
# Adding a new key-value pair
my_dict["email"] = "alice@example.com"
print("After adding email:", my_dict)
# Updating an existing value
my_dict["age"] = 31
print("After updating age:", my_dict)
Output
After updating age: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email': 'alice@example.com'}
Conclusion
Dictionaries in Python provide a powerful way to store and manage key-value pairs. You can easily create, access, add, and update values in dictionaries, making them versatile data structures for various applications.