Python: Creates a dictionary with the same keys as the given dictionary and values generated by running the given function for each value
Python dictionary: Exercise-74 with Solution
Write a Python program to create a dictionary with the same keys as the given dictionary and values generated by running the given function for each value.
Sample Solution:
Python Code:
# Define a function 'test' that takes a dictionary 'obj' and a function 'fn'.
def test(obj, fn):
# Use a dictionary comprehension to apply the function 'fn' to each value in the 'obj' dictionary.
# The result is a new dictionary with the same keys, where each value is transformed by 'fn'.
return dict((k, fn(v)) for k, v in obj.items())
# Create a dictionary 'users' where each key corresponds to a user and has associated data as a dictionary.
users = {
'Theodore': {'user': 'Theodore', 'age': 45},
'Roxanne': {'user': 'Roxanne', 'age': 15},
'Mathew': {'user': 'Mathew', 'age': 21},
}
# Print the original dictionary elements.
print("\nOriginal dictionary elements:")
print(users)
# Call the 'test' function to create a new dictionary with the same keys, but with 'age' values extracted.
print("\nDictionary with the same keys:")
print(test(users, lambda u: u['age']))
Sample Output:
Original dictionary elements: {'Theodore': {'user': 'Theodore', 'age': 45}, 'Roxanne': {'user': 'Roxanne', 'age': 15}, 'Mathew': {'user': 'Mathew', 'age': 21}} Dictionary with the same keys: {'Theodore': 45, 'Roxanne': 15, 'Mathew': 21}
Flowchart:
Python Code Editor:
Previous: Write a Python program to convert a list of dictionaries into a list of values corresponding to the specified key.
Next: Write a Python program to find all keys in the provided dictionary that have the given value.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/dictionary/python-data-type-dictionary-exercise-74.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics