Python Dictionary
A dictionary in Python is a built-in data type that stores data in key-value pairs. Each key is associated with a value, and the key must be unique and immutable (string, number, or tuple). The values can be of any data type.
Creating a Dictionary
You can create a dictionary using curly braces {}
or the dict()
constructor.
For example:
# Using curly braces
my_dict = {"name": "James Bond", "age": 35, "city": "Londons"}
# Using dict() constructor
another_dict = dict(name="Ethan Hunt", age=30, city="New York")
Accessing Values of Dictionary
You can access a dictionary’s values using their corresponding keys.
For example:
my_dict = {"name": "James Bond", "age": 35, "city": "London"}
print(my_dict["name"]) # Output: James Bond
# Using the get() method (returns None if the key is not found)
print(my_dict.get("age")) # Output: 35
Modifying a Dictionary
In Python, dictionaries are mutable, meaning you can modify them by adding, updating, or removing key-value pairs.
1. Adding Key-Value Pairs
You can add a new key-value pair by simply assigning a value to a new key. If the key already exists, the value will be updated.
For example:
my_dict = {"name": "James Bond", "age": 35}
# Adding a new key-value pair
my_dict["city"] = "London"
print(my_dict) # {'name': 'James Bond', 'age': 35, 'city': 'London'}
2. Updating Existing Values
You can update the value of an existing key by reassigning a new value.
For example:
my_dict = {"name": "James Bond", "age": 35}
# Updating an existing value
my_dict["age"] = 45
print(my_dict) # {'name': 'James Bond', 'age': 45}
Alternatively, you can use the update()
method to update multiple values at once or add new key-value pairs.
For example:
my_dict = {"name": "James Bond", "age": 35}
# Using update() to modify the dictionary
my_dict.update({"age": 55, "job": "spy"})
print(my_dict) # {'name': 'James Bond', 'age': 55, 'job': 'spy'}
3. Removing Key-Value Pairs
There are several ways to remove items from a dictionary.
(a) Using del
keyword
The del
keyword can remove a specific key-value pair to delete the entire dictionary. If the key does not exist, a KeyError
will be raised.
For example:
my_dict = {"name": "James Bond", "age": 35, "city": "London"}
# Deleting the key 'age'
del my_dict["age"]
print(my_dict) # Output: {'name': 'James Bond', 'city': 'London'}
# Deleting the entire dictionary
del my_dict
# print(my_dict)
# Trying to print the dictionary will raise a NameError.
# Because the dictionary doesn't exist
(b) Using pop()
The pop()
method removes a specified key-value pair from a dictionary and returns the associated value. If the key is not found, a KeyError
is raised unless a default value is provided.
For example:
my_dict = {"name": "James Bond", "age": 35, "city": "London"}
# Remove the 'age' key-value pair and return the value
removed_value = my_dict.pop("age")
print(removed_value) # Output: 35
print(my_dict) # Output: {'name': 'James Bond', 'city': 'London'}
(c) Using popitem()
The popitem()
method removes and returns the last inserted key-value pair.
For example:
my_dict = {"name": "James Bond", "age": 35, "city": "London"}
# Removing the last inserted key-value pair
last_item = my_dict.popitem()
print(last_item) # Output: ('city', 'London')
print(my_dict) # Output: {'name': 'James Bond', 'age': 35}
(d) Using clear()
The clear()
method removes all key-value pairs from the dictionary, leaving it empty.
For example:
my_dict = {"name": "James Bond", "age": 35, "city": "London"}
# Clearing all key-value pairs from the dictionary
my_dict.clear()
print(my_dict) # Output: {}
Looping through a Dictionary
In Python, you can loop through a dictionary using several different methods. You can iterate over the keys, values, or key-value pairs.
(1) Looping Through Keys
You can iterate over the keys of a dictionary directly or using the keys()
method.
The keys()
method returns a view object that displays a list of all the keys in a dictionary.
For example:
my_dict = {"name": "James Bond", "age": 35, "city": "London"}
# Looping through dictionary keys directly
for key in my_dict:
print(key)
# Looping through dictionary keys using the keys() method
for key in my_dict.keys():
print(key)
Output:
name
age
city
(2) Looping Through Values
You can loop through the values of a dictionary using the values()
method.
The values()
method returns a view object containing all the values in a dictionary.
For example:
my_dict = {"name": "James Bond", "age": 35, "city": "London"}
# Looping through dictionary values using the values() method
for value in my_dict.values():
print(value)
Output:
James Bond
35
London
(3) Looping Through Key-Value Pairs
You can iterate over both keys and values at the same time using the items()
method. This method returns key-value pairs as tuples.
For example:
my_dict = {"name": "James Bond", "age": 35, "city": "London"}
# Looping through key-value pairs
for key, value in my_dict.items():
print(key, value)
Output:
name James Bond
age 35
city London
(4) Looping with Index
If you need to loop through a Python dictionary while keeping track of the index, you can use the enumerate()
function in combination with the items()
method.
For example:
my_dict = {"name": "James Bond", "age": 35, "city": "London"}
# Looping through dictionary items using enumerate()
for index, (key, value) in enumerate(my_dict.items()):
print(f"Index: {index}, Key: {key}, Value: {value}")
Output:
Index: 0, Key: name, Value: James Bond
Index: 1, Key: age, Value: 35
Index: 2, Key: city, Value: London
Check if the key exists in a Dictionary
You can use the in
keyword to check if the key already exists in a dictionary.
For example:
my_dict = {"name": "James Bond", "age": 35, "city": "London"}
# Check if the key exists
if "name" in my_dict:
print("Key 'name' Exists")
else:
print("Key 'name' doesn't exist.")
Output:
Key 'name' Exists
Handling KeyErrors
in Python
A KeyError
occurs when you attempt to access a dictionary key that doesn’t exist.
Here are several methods to handle or prevent KeyError
:
(1) Using try-except
The most straightforward way to handle KeyErrors
is by using the try-except
block. This way, you can catch the exception and provide a fallback behavior.
For example:
my_dict = {"name": "James Bond", "age": 35}
try:
print(my_dict["gender"]) # Key 'gender' doesn't exist
except:
print("KeyError: The key 'gender' doesn't exist.")
Output:
KeyError: The key 'gender' doesn't exist.
(2) Using get()
Method
The get()
method allows you to access a key without raising a KeyError
. Instead, you can provide a default value that will be returned if the key is not found.
For example:
my_dict = {"name": "James Bond", "age": 35}
gender = my_dict.get("gender", "Not found")
print(gender) # Output: Not found
(3) Checking for key’s existence
Before accessing a key, you can check if it exists in the dictionary using the in
keyword. This avoids the need for exception handling.
For example:
my_dict = {"name": "James Bond", "age": 35}
if "gender" in my_dict:
print(my_dict["gender"])
else:
print("Key 'gender' not found.")
Output:
Key 'gender' not found.
(4) Using setdefault()
The setdefault()
method is useful when you need to add a key-value pair to a dictionary only if the key doesn’t already exist. It returns the value associated with the key. If the key doesn’t exist, it adds it with the specified value.
For example:
my_dict = {"name": "James Bond", "age": 35}
my_dict.setdefault("city", "London")
print(my_dict) # Output: {'name': 'James Bond', 'age': 35, 'city': 'London'}
my_dict.setdefault("city", "New York")
print(my_dict) # Output: {'name': 'James Bond', 'age': 35, 'city': 'London'}
Preventing Unintentional Overwrites in Python Dictionaries
If you try to add a key-value pair in a dictionary without checking if the key already exists, you may overwrite the existing data.
Here are some strategies to help you avoid unintentional overwrites in Python dictionaries:
(1) Check for Existing Keys with in
Keyword
Before adding a new key-value pair, you can check if the key already exists.
For example:
my_dict = {"name": "James Bond", "age": 35, "city": "London"}
if "city" in my_dict:
print("Key 'city' already exists.")
else:
my_dict["city"] = "New York"
Output:
Key 'city' already exists.
(2) Use the setdefault()
Method
The setdefault
method can be useful for ensuring a key is set to a default value only if it doesn’t already exist.
For example:
my_dict = {"name": "James Bond", "age": 35, "city": "London"}
my_dict.setdefault("city", "New York")
print(my_dict) # Output: {'name': 'James Bond', 'age': 35, 'city': 'London'}