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 in a list with the value from the second dictionary.
- 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 = {'Steven': 25, 'Jack': 21, 'Alice': 31, 'John': 41}
- second_dict = {'Steven': 31, 'Jack': 17, 'Bob': 33}
- new_dict = dicts_union_preserve(first_dict, second_dict)
- # new_dict: {'Steven': [25, 31], 'Jack': [21, 17], 'Alice': [31], 'John': [41], 'Bob': [33]}
- """
- # 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():
- # Check if the key already exists in the union dictionary
- if key in union_dict:
- # If the key already exists, preserve the value in a list
- union_dict[key].append(value)
- else:
- # If the key does not exist, add the key-value pair 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 in a list
- union_dict[key].append(value)
- else:
- # 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
- #This function iterates through the key-value pairs in both input dictionaries, adding the key-value pairs to the union dictionary.
- #It checks if the key already exists in the union dictionary, if it does it preserves the value in a list, if not it creates a new key #with the value in a list.
- #first_dict = {'Steven': 25, 'Jack': 21, 'Alice': 31, 'John': 41}
- #second_dict = {'Steven': 31, 'Jack': 17, 'Bob': 33}
- #new_dict = dicts_union_preserve(first_dict, second_dict)
- #print(new_dict)
Advertisement
Add Comment
Please, Sign In to add comment