Question: Create the function swap that takes a dictionary and returns a dictionary where the keys and values have been swapped. If the original dictionary contains

Create the function swap that takes a dictionary and returns a dictionary where the keys and values have been swapped. If the original dictionary contains an unhashable value, return the string:
Cannot swap the keys and values for this dictionary
.
Test Case 1
Using the given dictionary and function call below:
# test code below
if __name__=="__main__":
example_dict ={
1 : 'one',
2 : 'two',
3 : 'three'
}
swapped = swap(example_dict)
print(swapped)
Your script should print:
{'one': 1, 'two': 2, 'three': 3}
TRY IT
Test Case 2
Using the given dictionary and function call below:
# test code below
if __name__=="__main__":
example_dict ={
1 : [2,3],
4 : 'four',
5 : 'five'
}
swapped = swap(example_dict)
print(swapped)
Your script should print:
Cannot swap the keys and values for this dictionary
TRY IT
Test Case 3
Using the given dictionary and function call below:
# test code below
if __name__=="__main__":
example_dict ={
1 : 'one',
2 : {3 : 4},
5 : 'five'
}
swapped = swap(example_dict)
print(swapped)
Your script should print:
Cannot swap the keys and values for this dictionary
TRY IT
Test Case 4
Using the given dictionary and function call below:
# test code below
if __name__=="__main__":
example_dict ={
1 : 'one',
2 : 'two',
3 : (4,5)
}
swapped = swap(example_dict)
print(swapped)
Your script should print:
{'one': 1, 'two': 2,(4,5): 3}
TRY IT

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!