Understand Type Checking in Dictionaries
In this step, we'll explore the importance of type checking within dictionaries in Python. Dictionaries are versatile data structures that can store key-value pairs. However, to ensure the integrity and reliability of your code, it's crucial to understand how to check the types of keys and values stored in a dictionary.
Dictionaries in Python are defined using curly braces {}
. Each element in a dictionary consists of a key and a corresponding value, separated by a colon :
.
Let's start by creating a simple dictionary:
## Create a dictionary
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(my_dict)
Save the above code in a file named type_checking.py
within your ~/project
directory. You can use the VS Code editor to create and edit this file.
Now, execute the script using the following command in the terminal:
python ~/project/type_checking.py
You should see the following output:
{'name': 'Alice', 'age': 30, 'city': 'New York'}
In this dictionary, the keys are strings ("name"
, "age"
, "city"
) and the values are a string ("Alice"
), an integer (30
), and another string ("New York"
).
Type checking becomes important when you want to ensure that the data stored in your dictionary conforms to your expectations. For example, you might want to verify that the age is always an integer or that the name is always a string.
Let's consider a scenario where you want to add a new key-value pair to the dictionary, but you want to ensure that the value is of a specific type.
Open the type_checking.py
file in VS Code and modify it as follows:
## Create a dictionary
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
## Function to add a key-value pair with type checking
def add_item(dictionary, key, value, expected_type):
if isinstance(value, expected_type):
dictionary[key] = value
print(f"Added {key}: {value} to the dictionary.")
else:
print(f"Error: {key} must be of type {expected_type.__name__}.")
## Example usage
add_item(my_dict, "occupation", "Engineer", str)
add_item(my_dict, "salary", 75000, int)
add_item(my_dict, "is_active", True, bool)
add_item(my_dict, "height", "5.8", float) ## Intentionally incorrect type
print(my_dict)
In this code, we define a function add_item
that takes a dictionary, a key, a value, and an expected type as input. The function uses the isinstance()
function to check if the value is of the expected type. If it is, the key-value pair is added to the dictionary. Otherwise, an error message is printed.
Execute the script again:
python ~/project/type_checking.py
You should see the following output:
Added occupation: Engineer to the dictionary.
Added salary: 75000 to the dictionary.
Added is_active: True to the dictionary.
Error: height must be of type float.
{'name': 'Alice', 'age': 30, 'city': 'New York', 'occupation': 'Engineer', 'salary': 75000, 'is_active': True}
As you can see, the add_item
function successfully added the "occupation", "salary", and "is_active" key-value pairs to the dictionary because their values matched the expected types. However, it printed an error message for "height" because the provided value ("5.8") is a string, while the expected type was float
.
This example demonstrates the basic concept of type checking in dictionaries. In the following steps, we will explore more advanced techniques for ensuring type safety in your Python code.