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 dictmap
which takes a dictionary
d
and a function f
as input, and updates d
by replacing each value val
in the dictionary with f(val)
,
leaving the keys unchanged. Your function should modify d
but should not return anything explicitly (i.e. it should return None
implicitly by lacking a return statement). 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 starter code below which can be used to test your
dictmap
function:
def dictmap(d, f):
'''
Given a dictionary d and function f, mutate the values of the dictionary
to be the result of f(val).
'''
pass # your code here
def test(func):
dictionary = {"a":10, "b":-2}
expected = {"a":100, "b":4}
def square(x):
return x ** 2
out = func(dictionary, square)
assert out == None, f"Expected out to be None but got {out=}"
assert dictionary == expected, f'Expected {expected} but got {dictionary}'
if __name__ == "__main__":
# test for dictmap
test(dictmap)
print("done")
Relevant Readings about using functions as arguments.
Relevant Readings about assert
.
No file selected
Next Exercise: Caesar's Cipher