Table of contents

[Naive] 2281 · Merge dictionary

LintCode Nov 07, 2021 Viewed 5 Comments 0


  • Difficulty: Naive
  • Tag: Data Types (python), Dictionary (python)

For this question, we will provide two dictionaries dict_1 and dict_2. We have already written the merge function for you in The dict_1 and dict_2 of this function represent the initial dictionary. You need Add dict_1 to dict_2, and finally print dict_2.


The evaluation machine will execute your code by executing python {input_path}, and the test data will be placed in the file corresponding to input_path. You can see how the code works in

Example one

When the input dictionary is:


The print result is:


Example two

When the input dictionary is:

{'a': 102,'b': 542}
{'c': 412,'d': 869}

The print result is:

{'c': 412,'d': 869,'a': 102,'b': 542}


For the specific content of this question, please refer to the built-in dict.update() of Python official documentation Function to learn.


Solution 1: Python

Solution 1: Solution one: add cyclically


By looping through each key-value pair of the dictionary, and update it in dict_2.


def merge(dict_1, dict_2: dict) -> dict:
    for key, value in dict_1.items():
        dict_2[key] = value

Solution 2: Using the update method


With update method, you can update the key/value pair of dict_1 to dict_2.


def merge(dict_1, dict_2: dict) -> dict:
Updated Nov 07, 2021