Dictionary Map
Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
Define a function remap
which takes a dictionary
d
and a function func
as input, and returns a new dictionary with the
same keys, where the corresponding values have been determined by calling
the function func
on each value. Your function should not modify the input d
.
You may assume that all of the values in the dictionary are the proper type
to be accepted as input into the given function.
For example, consider the following starter program which can be used to test your code.
def remap(d, func):
pass # your code here
def square(x):
return x ** 2
def remap_test(func):
inp = {"a":-10, "b":float("inf"), "c": float("-inf")}
inp_copy = inp.copy()
exp = {"a":100, "b":float("inf"), "c": float("inf")}
res = func(inp, square)
assert res == exp, f"{exp=} but got {res=}"
assert inp == inp_copy, f'Expected input to be unchanged, got {inp=}'
import numpy as np
inp = {"carrots": [1, 2, 3], "broccoli": [4, 4, 4]}
# need to deep copy mutable values
inp_copy = {"carrots": [1, 2, 3], "broccoli": [4, 4, 4]}
exp = {"carrots": 2.0 , "broccoli": 4.0 }
res = func(inp, np.mean)
assert res == exp, f"{exp=} but got {res=}"
assert inp == inp_copy, f'Expected input to be unchanged, got {inp=}'
inp = {"6.s090": "fun", "python": "amazing", "lgo": "great"}
inp_copy = inp.copy()
exp = {"6.s090": "FUN", "python": "AMAZING", "lgo": "GREAT"}
res = func(inp, str.upper)
assert res == exp, f"{exp=} but got {res=}"
assert inp == inp_copy, f'Expected input to be unchanged, got {inp=}'
return True # correct!
if __name__ == "__main__":
# run tests for dictmap
result = remap_test(remap)
print(f"test passed? {result=}")
Relevant Readings about using functions as arguments.
Relevant Readings about assert
.
No file selected
Next Exercise: Second Largest Test