Dictionary Swap

The questions below are due on Sunday June 30, 2024; 10:00:00 PM.
 
You are not logged in.

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.

Write a function swap_keys that swaps two keys of a dictionary when supplied with a dictionary d, and two keys k1 and k2. You may assume that your program will only be run with dictionaries that contain both specified keys.

Relevant Readings - unpacking

Link to starter code file

def swap_keys(d, k1, k2):
    """
    Returns the dictionary after swapping the values associated with k1 and k2.

    Inputs:
      d (dict) - a dictionary that will be modified.
      k1 (any) - a dictionary key in d
      k2 (any) - a dictionary key in d

    """
    pass # your code here

if __name__=='__main__':
    # test cases -- feel free to add your own!
    d1 = {1: "hello", 2: "hi"}
    result1 = swap_keys(d1, 1, 2)
    print(f"Got {sorted(result1.items())}, Expected={sorted({1: 'hi', 2: 'hello'}.items())}")
    result2 = swap_keys(result1, 1, 2)
    print(f"Got {sorted(result2.items())}, Expexted={sorted({1: 'hello', 2: 'hi'}.items())})")
    # we should be modifying and returning a reference to the same dictionary,
    # not creating a new dictionary
    print(f"Expected that {d1} == {result1} == {result2}")

  No file selected

Next Exercise: Set Operations

Back to exercises