Dictionaries are another powerful data structure in Python. They allow you to store data in key-value pairs, meaning you can associate a value with a specific key. This makes dictionaries incredibly useful for tasks where you need to look up values quickly.
You can create a dictionary using curly braces {}
, where each key is paired with a value using a colon:
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
To access a value in a dictionary, you use the key inside square brackets:
print(my_dict["name"]) # Outputs: Alice
Like lists, dictionaries are mutable, so you can add, modify, or remove key-value pairs:
my_dict["age"] = 26 # Update the value of "age"
my_dict["email"] = "alice@example.com" # Add a new key-value pair
del my_dict["city"] # Remove the key "city" and its value
You can also loop through dictionaries to access keys and values:
for key, value in my_dict.items():
print(key, ":", value)
Create a dictionary that stores information about your favorite book. Include keys such as "title", "author", and "year". Then, add a new key for "genre" and print the updated dictionary.