Tutorialspoint
Problem
Solution
Submissions

Merge Two Dictionaries into One

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 5

Write a Python program that merges two dictionaries into one. If there are duplicate keys, the value from the second dictionary should overwrite the value from the first.

Example 1
  • Input 1: {'a': 1, 'b': 2}
  • Input 2: {'b': 3, 'c': 4}
  • Output: {'a': 1, 'b': 3, 'c': 4}
  • Explanation:
    • Step 1: Take the first dictionary {'a': 1, 'b': 2} and the second dictionary {'b': 3, 'c': 4}.
    • Step 2: Create a new dictionary with all key-value pairs from the first dictionary: {'a': 1, 'b': 2}.
    • Step 3: Add all key-value pairs from the second dictionary, overwriting any existing keys.
    • Step 4: The key 'b' appears in both dictionaries, so its value is updated to 3 from the second dictionary.
    • Step 5: Return the merged dictionary {'a': 1, 'b': 3, 'c': 4}.
Example 2
  • Input 1: {'x': 5, 'y': 2}
  • Input 2: {'y': 8, 'z': 9}
  • Output: {'x': 5, 'y': 8, 'z': 9}
  • Explanation:
    • Step 1: Take the first dictionary {'x': 5, 'y': 2} and the second dictionary {'y': 8, 'z': 9}.
    • Step 2: Create a new dictionary with all key-value pairs from the first dictionary: {'x': 5, 'y': 2}.
    • Step 3: Add all key-value pairs from the second dictionary, overwriting any existing keys.
    • Step 4: The key 'y' appears in both dictionaries, so its value is updated to 8 from the second dictionary.
    • Step 5: Return the merged dictionary {'x': 5, 'y': 8, 'z': 9}.
Constraints
  • 1 ≤ len(d1), len(d2) ≤ 10^3
  • -10^5 ≤ d1[key], d2[key] ≤ 10^5
  • Time Complexity: O(n), where n is the total number of key-value pairs
  • Space Complexity: O(n)
Dictionaries Deloitte
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the ** operator to unpack and merge dictionaries.
  • Use the update() method to merge dictionaries in place.
  • Use dictionary comprehension to combine the dictionaries.

Steps to solve by this approach:

 Step 1: Use dictionary unpacking with the ** operator.
 Step 2: Unpack the first dictionary (d1) into a new dictionary.
 Step 3: Unpack the second dictionary (d2) into the same new dictionary.
 Step 4: When keys overlap, values from d2 will override values from d1.
 Step 5: Return the merged dictionary containing all key-value pairs.
 Step 6: This approach is more concise than using the update() method.
 Step 7: Example: {'a': 1, 'b': 2} and {'b': 3, 'c': 4} merge to {'a': 1, 'b': 3, 'c': 4}.

Submitted Code :