Applying the Function to Dictionaries and Lists
Now that we have created the versatile handle_data()
function, let's see how we can apply it to both dictionaries and lists.
Applying the Function to a Dictionary
Suppose we have a dictionary representing a person's information:
person = {
"name": "John Doe",
"age": 35,
"occupation": "Software Engineer"
}
We can pass this dictionary to the handle_data()
function, and it will print the key-value pairs:
handle_data(person)
Output:
Key: name, Value: John Doe
Key: age, Value: 35
Key: occupation, Value: Software Engineer
Applying the Function to a List
Now, let's apply the handle_data()
function to a list of fruits:
fruits = ["apple", "banana", "cherry"]
handle_data(fruits)
Output:
apple
banana
cherry
If you pass an input that is neither a dictionary nor a list, the handle_data()
function will print an error message:
handle_data(42)
Output:
Input must be a dictionary or a list.
By using the handle_data()
function, you can write code that is more flexible and can work with different data structures, making your Python programs more versatile and maintainable.