Skip to main content
 首页 » 编程设计

python之替换重复键时选择要替换字典中的哪个值

2024年10月24日7cmt

问题: 给定两个名为 dict1 和 dict2 的词典,使用“For”循环编写代码将 dict1 的所有项添加到 dict2。如果dict1的key在dict2中已经存在,则不要添加到dict2中。

例如:

dict1 = {1: "ab", 2: "cd"} 
 
dict2 = {1: "ef", 3: "gh"} 

运行你的代码后,dict2 应该是

dict2 = {1: "ef", 3: "gh", 2: "cd"} 

因为 dict1 中 1: "ab" 的键已经存在于 dict2 中。

我的代码是:

dict1 = {1: "ab", 2: "cd"} 
dict2 = {1: "ef", 3: "gh"} 
for i in [dict1]: 
    if i not in [dict2]: 
        dict2.update(dict1) 
        print(dict2) 

当我运行它时,我的 dict2 是 dict2 = {1: "ab", 2: "cd", 3: "gh"}

如何制作 dict2 = {1: "ef", 2: "cd", 3: "gh"}

请您参考如下方法:

这样的事情怎么样?

for i in dict1: 
    if i not in dict2: 
        dict2[i] = dict1[i] 
#=> {1: 'ef', 2: 'cd', 3: 'gh'}