Intern — Middle
Removing an item from a dictionary without prior key check
livecode
Task condition
Complete the delete function, which removes an element with the specified key key from the given dictionary d. If such a key does not exist, an exception should not be generated. It is forbidden to use conditional statements if to check for the presence of the key, as well as try/except blocks or the contextlib.suppress utility.
import json
def delete(d: dict, key: str) -> dict:
"""Deletes a key from a dictionary if it exists.
Args:
d: The dictionary to modify.
key: The key to delete.
Returns:
The modified dictionary.
"""
if key in d:
del d[key]
return d
if __name__ == "__main__":
d_str, k = input().split(';')
d = json.loads(d_str)
print(dict(sorted(delete(d, k).items())))