GeorgeDI

dicts_union_preserve

Jan 12th, 2023
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. def dicts_union_preserve(first_dict, second_dict):
  2. """
  3. Function that takes in two dictionaries as arguments, and returns a new dictionary that contains all key-value pairs from both input dictionaries.
  4. If a key already exists in the first dictionary, its value will be preserved instead of being overwritten.
  5.  
  6. Args:
  7. first_dict (dict): The first dictionary to be merged
  8. second_dict (dict): The second dictionary to be merged
  9.  
  10. Returns:
  11. dict: A new dictionary containing all key-value pairs from both input dictionaries
  12.  
  13. Example:
  14. first_dict = {'a': 1, 'b': 2, 'c': 3}
  15. second_dict = {'c': 4, 'd': 5, 'e': 6}
  16. result = dicts_union_preserve(first_dict, second_dict)
  17. print(result) # {'a': 1, 'b': 2, 'c': 3, 'd': 5, 'e': 6}
  18.  
  19. """
  20. # Create a new dictionary to store the union of key-value pairs
  21. union_dict = {}
  22.  
  23. # Iterate through the key-value pairs in the first dictionary
  24. for key, value in first_dict.items():
  25. # Add the key-value pairs to the union dictionary
  26. union_dict[key] = value
  27.  
  28. # Iterate through the key-value pairs in the second dictionary
  29. for key, value in second_dict.items():
  30. # Check if the key already exists in the union dictionary
  31. if key in union_dict:
  32. # If the key already exists, preserve the value from the first dictionary
  33. continue
  34. # If the key does not exist, add the key-value pair to the union dictionary
  35. union_dict[key] = value
  36.  
  37. # Return the union dictionary
  38. return union_dict
  39.  
Advertisement
Add Comment
Please, Sign In to add comment