Key-Value Pairs - Dictionary in Python
In Python, a dictionary is an unordered collection of key-value pairs. Dictionaries are one of the most versatile data structures in Python and are used to store and retrieve data efficiently. This article explains the concept of dictionaries, their properties, and how to use them with examples.
1. What is a Dictionary?
A dictionary in Python is a collection of items stored as key-value pairs. Each key in a dictionary is unique, and it maps to a specific value. The key-value structure allows you to quickly retrieve values based on their corresponding keys.
Example: Defining a Dictionary
# Defining a dictionary
person = {
"name": "John",
"age": 30,
"profession": "Engineer"
}
print(person) # Outputs: {'name': 'John', 'age': 30, 'profession': 'Engineer'}
2. Accessing Values in a Dictionary
You can access the values in a dictionary by using their corresponding keys. If the key does not exist, Python raises a KeyError.
Example: Accessing Values
# Accessing values using keys
person = {"name": "John", "age": 30, "profession": "Engineer"}
print(person["name"]) # Outputs: John
print(person["age"]) # Outputs: 30
Example: Handling KeyError
# Handling a KeyError
person = {"name": "John", "age": 30}
try:
print(person["address"]) # This will raise a KeyError
except KeyError as e:
print(f"Error: {e}") # Outputs: Error: 'address'
3. Adding and Modifying Key-Value Pairs
You can add new key-value pairs to a dictionary or modify the value of an existing key by simply assigning a new value to the key.
Example: Adding and Modifying Key-Value Pairs
# Adding a new key-value pair
person = {"name": "John", "age": 30}
person["profession"] = "Engineer" # Adds the new key 'profession' with value 'Engineer'
print(person) # Outputs: {'name': 'John', 'age': 30, 'profession': 'Engineer'}
# Modifying an existing key-value pair
person["age"] = 31 # Updates the value of the 'age' key
print(person) # Outputs: {'name': 'John', 'age': 31, 'profession': 'Engineer'}
4. Removing Key-Value Pairs
To remove a key-value pair from a dictionary, you can use the del statement or the pop() method.
Example: Using del to Remove a Key-Value Pair
# Using del to remove a key-value pair
person = {"name": "John", "age": 30, "profession": "Engineer"}
del person["age"] # Removes the 'age' key-value pair
print(person) # Outputs: {'name': 'John', 'profession': 'Engineer'}
Example: Using pop() to Remove a Key-Value Pair
# Using pop to remove a key-value pair and return the value
person = {"name": "John", "age": 30, "profession": "Engineer"}
age = person.pop("age") # Removes 'age' and returns its value
print(age) # Outputs: 30
print(person) # Outputs: {'name': 'John', 'profession': 'Engineer'}
5. Looping Through a Dictionary
You can loop through a dictionary to access its keys, values, or both.
Example: Looping Through Keys and Values
# Looping through keys and values
person = {"name": "John", "age": 30, "profession": "Engineer"}
for key, value in person.items():
print(f"{key}: {value}")
# Outputs:
# name: John
# age: 30
# profession: Engineer
6. Dictionary Methods
Python dictionaries come with various built-in methods for performing common tasks.
Example: Using get() Method
# Using the get() method
person = {"name": "John", "age": 30}
print(person.get("name")) # Outputs: John
print(person.get("address", "Not Available")) # Outputs: Not Available (default value if key does not exist)
Example: Using keys(), values(), and items()
# Using keys(), values(), and items() methods
person = {"name": "John", "age": 30, "profession": "Engineer"}
print(person.keys()) # Outputs: dict_keys(['name', 'age', 'profession'])
print(person.values()) # Outputs: dict_values(['John', 30, 'Engineer'])
print(person.items()) # Outputs: dict_items([('name', 'John'), ('age', 30), ('profession', 'Engineer')])
7. Conclusion
Dictionaries are an essential data structure in Python that allow for efficient storage and retrieval of data in key-value pairs. Understanding how to use and manipulate dictionaries is crucial for handling complex data and solving real-world problems in Python.