Introduction
In Python, a dictionary is a collection of key-value pairs. Sometimes, we need to create a dictionary from a list where the keys are the elements of the list and the values are the result of applying a function to those elements. In this challenge, you will create a function that maps the values of a list to a dictionary using a function.
Map List to Dictionary
Write a Python function called map_dictionary(itr, fn) that takes two parameters:
itr: a list of valuesfn: a function that takes a value as input and returns a value as output
The function should return a dictionary where the key-value pairs consist of the original value as the key and the result of the function as the value.
To solve this problem, follow these steps:
- Use
map()to applyfnto each value of the list. - Use
zip()to pair original values to the values produced byfn. - Use
dict()to return an appropriate dictionary.
def map_dictionary(itr, fn):
return dict(zip(itr, map(fn, itr)))
map_dictionary([1, 2, 3], lambda x: x * x) ## { 1: 1, 2: 4, 3: 9 }
Summary
In this challenge, you learned how to create a dictionary from a list where the keys are the elements of the list and the values are the result of applying a function to those elements. You used the map(), zip(), and dict() functions to solve the problem.