📜  Python – 从其他字典中替换字典值

📅  最后修改于: 2022-05-13 01:55:17.865000             🧑  作者: Mango

Python – 从其他字典中替换字典值

给定两个字典,如果键存在于其他字典中,则更新其他字典中的值。

方法#1:使用循环

这是可以执行此任务的粗暴方式。在此,我们为目标字典中的每个键运行一个循环,并在该值存在于其他字典中的情况下进行更新。

Python3
# Python3 code to demonstrate working of 
# Replace dictionary value from other dictionary
# Using loop
  
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing updict
updict = {"Gfg"  : 10, "Best" : 17}
  
for sub in test_dict:
      
    # checking if key present in other dictionary
    if sub in updict:
        test_dict[sub]  = updict[sub]
  
# printing result 
print("The updated dictionary: " + str(test_dict))


Python3
# Python3 code to demonstrate working of 
# Replace dictionary value from other dictionary
# Using dictionary comprehension
  
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing updict
updict = {"Gfg"  : 10, "Best" : 17}
  
res = {key: updict.get(key, test_dict[key]) for key in test_dict}
  
# printing result 
print("The updated dictionary: " + str(res))


输出

方法#2:使用字典理解

这是可以执行此任务的一种线性方法。在此,我们迭代所有字典值并在字典理解中以单线方式更新。

Python3

# Python3 code to demonstrate working of 
# Replace dictionary value from other dictionary
# Using dictionary comprehension
  
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing updict
updict = {"Gfg"  : 10, "Best" : 17}
  
res = {key: updict.get(key, test_dict[key]) for key in test_dict}
  
# printing result 
print("The updated dictionary: " + str(res)) 
输出