[Naive] 2281 · Merge dictionary
Description
- Difficulty: Naive
For this question, we will provide two dictionaries dict_1
and dict_2
. We have already written the merge
function for you in solution.py
. 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
.
Data guarantee, the key
values in both dictionaries are unique
Example
The evaluation machine will execute your code by executing python main.py {input_path}
, and the test data will be placed in the file corresponding to input_path
. You can see how the code works in main.py
.
Example one
When the input dictionary is:
{'China':'HangZhou','America':'NewYork'}
{'England':'London','Russia':'Moscow'}
The print result is:
{'England':'London','Russia':'Moscow','China':'HangZhou','America':'NewYork'}
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}
Hint
For the specific content of this question, please refer to the built-in dict.update()
of Python official documentation Function to learn.
Solution
Solution 1: Python
Solution 1: Solution one: add cyclically
Ideas
By looping through each key-value pair of the dictionary, and update it in dict_2
.
Python
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
Ideas
With update
method, you can update the key/value pair of dict_1
to dict_2
.
Python
def merge(dict_1, dict_2: dict) -> dict:
dict_2.update(dict_1)