GeorgeDI

T1

Jan 12th, 2023
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 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 in a list with 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 = {'Steven': 25, 'Jack': 21, 'Alice': 31, 'John': 41}
  15. second_dict = {'Steven': 31, 'Jack': 17, 'Bob': 33}
  16. new_dict = dicts_union_preserve(first_dict, second_dict)
  17. # new_dict: {'Steven': [25, 31], 'Jack': [21, 17], 'Alice': [31], 'John': [41], 'Bob': [33]}
  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. # Check if the key already exists in the union dictionary
  26. if key in union_dict:
  27. # If the key already exists, preserve the value in a list
  28. union_dict[key].append(value)
  29. else:
  30. # If the key does not exist, add the key-value pair to the union dictionary
  31. union_dict[key] = [value]
  32.  
  33. # Iterate through the key-value pairs in the second dictionary
  34. for key, value in second_dict.items():
  35. # Check if the key already exists in the union dictionary
  36. if key in union_dict:
  37. # If the key already exists, preserve the value in a list
  38. union_dict[key].append(value)
  39. else:
  40. # If the key does not exist, add the key-value pair to the union dictionary
  41. union_dict[key] = [value]
  42.  
  43. # Return the union dictionary
  44. return union_dict
  45.  
  46.  
  47. #This function iterates through the key-value pairs in both input dictionaries, adding the key-value pairs to the union dictionary.
  48. #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.
  49.  
  50. #first_dict = {'Steven': 25, 'Jack': 21, 'Alice': 31, 'John': 41}
  51. #second_dict = {'Steven': 31, 'Jack': 17, 'Bob': 33}
  52. #new_dict = dicts_union_preserve(first_dict, second_dict)
  53. #print(new_dict)
Advertisement
Add Comment
Please, Sign In to add comment