Junior — Senior
Creating a merge_dicts function without explicit key existence check
livecode
Task condition
Write a function merge_dicts that merges two dictionaries: all key-value pairs from the second dictionary are added to the first, but only if the corresponding key does not already exist in the first. It is not recommended to use the if operator to check for the presence of a key during implementation.
import json
def merge_dicts(first_dict: dict, second_dict: dict) -> dict:
for key, value in second_dict.items():
first_dict[key] = value
return first_dict
if __name__ == "__main__":
first_str, second_str = input().split(';')
first_dict = json.loads(first_str)
second_dict = json.loads(second_str)
print(dict(sorted(merge_dicts(first_dict, second_dict).items())))
The input consists of two JSON strings separated by a semicolon. The program should output the resulting dictionary sorted by keys.