Dictionaries are a way to store and organize related pieces of data in Python. They are useful when you need to quickly look up a value based on a specific key, just like looking up a word in a dictionary to find its meaning.
Each item in a dictionary is a key-value pair, where the key is a unique identifier, and the value is the data associated with that key.
Creating Dictionaries
To create a dictionary, you use curly braces {}
:
my_dict = {"name": "Alice", "age": 25, "city": "Paris"}
In this example:
,"name" , and"age"
are the keys."city"
,"Alice" , and25
are the values associated with those keys."Paris"
Accessing, adding, updating, and removing key-value pairs
Accessing a value:
To get a value, you use the key inside square brackets []
print(my_dict["name"]) # Output: Alice
Adding a new key-value pair:
You can add new pairs to the dictionary by assigning a value to a new key:
my_dict["job"] = "Engineer" # Adds a new key "job" with the value "Engineer"
Updating a value:
You can change the value of an existing key:
my_dict["age"] = 26 # Updates the value of "age" to 26
Removing a key-value pair:
You can remove a pair using the del
del my_dict["city"] # Removes the key "city" and its associated value
Iterating over keys, values, and items
You can loop through a dictionary to access its keys, values, or both:
Keys:
for key in my_dict:
print(key)
This will print each key in the dictionary.
Values:
for value in my_dict.values():
print(value)
This will print each value in the dictionary.
Key-value pairs:
for key, value in my_dict.items():
print(f"{key}: {value}")
This will print each key along with its associated value.
Nested Dictionaries
A nested dictionary is a dictionary where the value of a key is another dictionary. This is useful when you want to organize data more hierarchically.
my_dict = {
"person": {"name": "Bob", "age": 30},
"city": "New York"
}
In this example, the value for the "person"
"name"
"age"
print(my_dict["person"]["name"]) # Output: Bob
Summary
- Dictionaries are used to store key-value pairs, making it easy to look up data using a key.
- You can create, access, update, and remove key-value pairs.
- You can iterate over the keys, values, or both.
- Nested dictionaries allow you to store more complex, hierarchical data.
Dictionaries are a powerful way to organize and manage data in Python!