Python Dictionaries
A dictionary in Python is an unordered collection of data in the form of key-value pairs. It is one of the most powerful and flexible data structures in Python. Dictionaries are defined by enclosing a comma-separated list of key-value pairs within curly braces {}
. Each key-value pair is separated by a colon :
.
Definition and Characteristics of Dictionaries
- Unordered: The elements in a dictionary are not stored in a sequence, and their order may vary.
- Mutable: Dictionaries are changeable, meaning you can add, modify, and remove elements after their creation.
- Indexed by Keys: Each value in a dictionary is associated with a unique key, which is used to access that value.
- Keys Must Be Immutable: Keys can be any immutable data type like strings, numbers, or tuples, but not lists or other dictionaries.
Let's see how to create a basic dictionary in Python:
Example 1: Creating a Dictionary
# Example: Creating a Dictionary
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print("Dictionary:", person)
Output
Accessing Values in a Dictionary
You can access the values in a dictionary by referring to their keys:
# Example: Accessing Dictionary Values
print("Name:", person["name"])
print("Age:", person.get("age"))
Output
Modifying a Dictionary
You can add new items or change existing ones by using the assignment operator:
Example: Modifying a Dictionary
person["age"] = 26 # Modifying existing value
person["email"] = "alice@example.com" # Adding a new key-value pair
print("Updated Dictionary:", person)
Output
Deleting Items from a Dictionary
Dictionaries allow you to remove items using the del
keyword or the pop()
method:
del person["city"] # Deleting an item by key
removed_email = person.pop("email", "Not Found") # Removing with pop()
print("After Deletion:", person)
print("Removed Email:", removed_email)
Output
Looping Through a Dictionary
You can loop through a dictionary to access its keys, values, or both:
for key, value in person.items():
print(f"{key}: {value}")
Output
Common Dictionary Methods
keys()
: Returns a view object containing the dictionary's keys.values()
: Returns a view object containing the dictionary's values.items()
: Returns a view object containing the dictionary's key-value pairs.update()
: Updates the dictionary with elements from another dictionary or from a set of key-value pairs.clear()
: Removes all items from the dictionary.copy()
: Returns a shallow copy of the dictionary.
Let's see how some of these methods work:
Using Dictionary Methods
person.update({"city": "Boston", "age": 27})
print("Updated Person:", person)
print("Keys:", list(person.keys()))
print("Values:", list(person.values()))
print("Items:", list(person.items()))
Output
Dictionaries are an essential data structure in Python, offering a powerful way to store and manage data using key-value pairs. They are highly versatile and efficient for quick data lookups, modifications, and complex data manipulations. Understanding dictionaries and their methods is crucial for effective Python programming.