【入门】2281 · 合并字典

LintCode 领扣 2021-10-18 阅读 23 评论 0

描述

  • 难度: 入门
  • 标签: 数据类型, 字典

本题我们会提供两个字典 dict_1dict_2,我们已经在 solution.py 中帮你写好了 merge 函数,该函数的 dict_1dict_2 代表初始字典,你需要把 dict_1 添加到 dict_2 里面,最后将 dict_2 打印。

样例

评测机将会通过执行 python main.py {input_path} 来执行你的代码,测试数据将被放在 input_path 所对应的文件中。你可以在 main.py 中了解代码是如何运行的。

样例一

当输入字典为:

{'China': 'HangZhou', 'America': 'NewYork'}
{'England': 'London', 'Russia': 'Moscow'}

打印结果为:

{'England': 'London', 'Russia': 'Moscow', 'China': 'HangZhou', 'America': 'NewYork'}

样例二

当输入字典为:

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

打印结果为:

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

提示

本题具体内容可参考 Python 官方文档dict.update() 内置函数来进行学习。

题解

题解 1: Python

解法一:循环遍历添加

解题思路

通过循环遍历字典种每一个键值对,在 dict_2 中更新

源代码

Python

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

解法二:使用 update 方法

解题思路

Python 字典 update 函数把字典参数 dict_1 的 key/value(键/值) 对更新到字典 dict_2 里。

源代码

Python

def merge(dict_1, dict_2: dict) -> dict:
    dict_2.update(dict_1)

知识要点

基本语法:循环、update

while 循环

Python 中 while 语句的一般形式:

while 布尔表达式: 
    # 循环内容 

需要注意冒号和缩进。只要布尔表达式为 True,循环内容就会一直执行下去。

示例:

number = 5;   
while number < 10: 
    print('value of number :', number) 
    number += 1 

执行以上脚本,输出结果如下:

value of number : 5 
value of number : 6 
value of number : 7 
value of number : 8 
value of number : 9 

for 循环

Python for 循环可以遍历任何可迭代对象,如一个列表或者一个字符串。

for 循环的一般格式如下:

for 循环变量 in 可迭代对象: 
    # 循环内容 

示例:

languages = ['C', 'C++', 'Java', 'Python']  
for language in languages: 
    print(language) 

执行以上脚本,输出结果如下:

C 
C++ 
Java 
Python 

update 方法

Python 字典 update 函数把字典参数 dict2 的 key/value (键/值) 对更新到字典 dict 里。

示例:

dict = {'Name': 'jiuzhang', 'Age': 37}
dict2 = {'Sex': 'male'}

dict.update(dict2)
print ("更新字典 dict : ", dict)

执行以上脚本,输出结果如下:

更新字典 dict :  {'Name': 'jiuzhang', 'Age': 37, 'Sex': 'male'}
最后更新 2021-10-18
MIP.watch('startSearch', function (newVal, oldVal) { if(newVal) { var keyword = MIP.getData('keyword'); console.log(keyword); // 替换当前历史记录,新增 MIP.viewer.open('/s/' + keyword, {replace: true}); setTimeout(function () { MIP.setData({startSearch: false}) }, 1000); } }); MIP.watch('goHome', function (newVal, oldVal) { MIP.viewer.open('/', {replace: false}); });