Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def dicts_union_preserve(first_dict, second_dict):
- """
- Function that takes in two dictionaries as arguments, and returns a new dictionary that contains all key-value pairs from both input dictionaries.
- If a key already exists in the first dictionary, its value will be preserved instead of being overwritten.
- Args:
- first_dict (dict): The first dictionary to be merged
- second_dict (dict): The second dictionary to be merged
- Returns:
- dict: A new dictionary containing all key-value pairs from both input dictionaries
- Example:
- first_dict = {'a': 1, 'b': 2, 'c': 3}
- second_dict = {'c': 4, 'd': 5, 'e': 6}
- result = dicts_union_preserve(first_dict, second_dict)
- print(result) # {'a': 1, 'b': 2, 'c': 3, 'd': 5, 'e': 6}
- """
- # Create a new dictionary to store the union of key-value pairs
- union_dict = {}
- # Iterate through the key-value pairs in the first dictionary
- for key, value in first_dict.items():
- # Add the key-value pairs to the union dictionary
- union_dict[key] = value
- # Iterate through the key-value pairs in the second dictionary
- for key, value in second_dict.items():
- # Check if the key already exists in the union dictionary
- if key in union_dict:
- # If the key already exists, preserve the value from the first dictionary
- continue
- # If the key does not exist, add the key-value pair to the union dictionary
- union_dict[key] = value
- # Return the union dictionary
- return union_dict
Advertisement
Add Comment
Please, Sign In to add comment