GeorgeDI

dicts_union_override

Jan 12th, 2023
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. def dicts_union_override(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 overridden by the value from the second dictionary.
  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_override(first_dict, second_dict)
  17. print(result) # {'a': 1, 'b': 2, 'c': 4, 'd': 5, 'e': 6}
  18.  
  19. """
  20. # Create a copy of the first dictionary
  21. union_dict = first_dict.copy()
  22.  
  23. # Iterate through the key-value pairs in the second dictionary
  24. for key, value in second_dict.items():
  25. # Add the key-value pairs to the union dictionary
  26. union_dict[key] = value
  27.  
  28. # Return the union dictionary
  29. return union_dict
Advertisement
Add Comment
Please, Sign In to add comment