Question: USE PYTHON3; DO NOT IMPORT ANY PACKAGES Create a function that processes the input dictionary according to the following rules. The input dictionary will only
USE PYTHON3; DO NOT IMPORT ANY PACKAGES
Create a function that processes the input dictionary according to the following rules. The input dictionary will only have non-negative integers for the keys and values.
For each key in the dictionary:
-
If the key is odd, remove this key-value pair from the dictionary
-
Else if the square of this key exists in the dictionary (as a key), square the current key's corresponding value. Do not modify the key itself.
-
Else if the square root of this key exists in the dictionary (as a key), square root the current key's corresponding value and convert it to int (with int()). Do not modify the key itself.
-
Otherwise, don't modify this key and its corresponding value.
Note: Be careful with modifying the existing dictionary while looping through it. You may want to create a new dictionary instead.
Example:
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6} -> {2: 4, 4: 2, 6: 6}
Explanation:
| Input | Reason | Output |
| 1: 1 | odd key, remove | |
| 2: 2 | square of 2 (= 4) exists as a key, square the value | 2: 4 |
| 3: 3 | odd key, remove | |
| 4: 4 | square root of 4 (= 2) exists as a key, square root the value and convert to int | 4: 2 |
| 5: 5 | odd key, remove | |
| 6: 6 | square or square root of 6 do not exist as a key, make no change | 6: 6 |
You can use one line dictionary comprehension if you choose
def process_dict(data):
"""
>>> process_dict({1: 1, 2: 2, 3: 3, 4: 4})
{2: 4, 4: 2}
>>> process_dict({})
{}
>>> process_dict({10: 10, 100: 100, 4: 1})
{10: 100, 100: 10, 4: 1}
"""
# YOUR CODE GOES HERE #
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
