Understanding Python Dictionaries
What is a Python Dictionary?
A Python dictionary is a collection of key-value pairs, where each key is unique and associated with a corresponding value. Dictionaries are denoted by curly braces {}
and the key-value pairs are separated by colons :
.
## Example of a Python dictionary
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
In the above example, the keys are "name"
, "age"
, and "city"
, and the corresponding values are "John Doe"
, 30
, and "New York"
, respectively.
Key-Value Pairs
The key in a dictionary can be of any immutable data type, such as strings, numbers, or tuples. The values can be of any data type, including mutable types like lists or other dictionaries.
## Example of a dictionary with different data types
mixed_dict = {
"name": "Jane Doe",
"age": 25,
"hobbies": ["reading", "hiking", "painting"],
"address": {
"street": "123 Main St",
"city": "San Francisco",
"state": "CA"
}
}
Accessing and Modifying Dictionaries
You can access the values in a dictionary using the key, and you can also add, modify, or remove key-value pairs.
## Accessing dictionary values
print(person["name"]) ## Output: "John Doe"
print(mixed_dict["hobbies"]) ## Output: ["reading", "hiking", "painting"]
## Modifying dictionary values
person["age"] = 31
mixed_dict["hobbies"].append("cooking")
## Adding new key-value pairs
person["email"] = "john.doe@example.com"
mixed_dict["occupation"] = "Software Engineer"
## Removing key-value pairs
del person["email"]
mixed_dict.pop("occupation")
Common Dictionary Methods
Python dictionaries provide a variety of built-in methods to perform various operations, such as getting the keys, values, or items, checking the existence of a key, and more.
## Getting the keys, values, and items of a dictionary
print(person.keys()) ## Output: dict_keys(['name', 'age', 'city'])
print(person.values()) ## Output: dict_values(['John Doe', 30, 'New York'])
print(person.items()) ## Output: dict_items([('name', 'John Doe'), ('age', 30), ('city', 'New York')])
## Checking if a key exists in a dictionary
if "age" in person:
print("The person's age is", person["age"])
By understanding the basics of Python dictionaries, you can efficiently traverse and manipulate them to solve a variety of problems.