Understanding Python Dictionaries
Python dictionaries are powerful data structures that allow you to store and retrieve data in key-value pairs. They are highly versatile and are widely used in various programming tasks, from data manipulation to building complex applications.
What is a Python Dictionary?
A Python dictionary is an unordered collection of key-value pairs. Each key in the dictionary must be unique, and it is used to access the corresponding value. Dictionaries are defined using curly braces {}
, with each key-value pair separated by a colon :
.
## Example of a Python dictionary
person = {
"name": "John Doe",
"age": 35,
"city": "New York"
}
In the example above, the dictionary person
has three key-value pairs: "name"
is the key, and "John Doe"
is the corresponding value; "age"
is the key, and 35
is the corresponding value; and "city"
is the key, and "New York"
is the corresponding value.
Accessing Dictionary Elements
You can access the values in a dictionary using their corresponding keys. This is done by specifying the key within square brackets []
after the dictionary name.
## Accessing dictionary elements
print(person["name"]) ## Output: "John Doe"
print(person["age"]) ## Output: 35
print(person["city"]) ## Output: "New York"
Adding, Modifying, and Removing Elements
Dictionaries are mutable, which means you can add, modify, and remove key-value pairs as needed.
## Adding a new key-value pair
person["email"] = "johndoe@example.com"
## Modifying an existing value
person["age"] = 36
## Removing a key-value pair
del person["city"]
Iterating over Dictionaries
You can iterate over the keys, values, or both key-value pairs in a dictionary using various methods.
## Iterating over keys
for key in person:
print(key)
## Iterating over values
for value in person.values():
print(value)
## Iterating over key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
Understanding the basic concepts and usage of Python dictionaries is crucial for effectively handling and troubleshooting KeyError
issues, which we will explore in the next section.