Python – 从其他字典中替换字典值
给定两个字典,如果键存在于其他字典中,则更新其他字典中的值。
Input : test_dict = {“Gfg” : 5, “is” : 8, “Best” : 10, “for” : 8, “Geeks” : 9},
updict = {“Geeks” : 10, “Best” : 17}
Output : {‘Gfg’: 5, ‘is’: 8, ‘Best’: 17, ‘for’: 8, ‘Geeks’: 10}
Explanation : “Geeks” and “Best” values updated to 10 and 17.
Input : test_dict = {“Gfg” : 5, “is” : 8, “Best” : 10, “for” : 8, “Geeks” : 9},
updict = {“Geek” : 10, “Bet” : 17}
Output : {‘Gfg’: 5, ‘is’: 8, ‘Best’: 10, ‘for’: 8, ‘Geeks’: 9}
Explanation : No values matched, hence original dictionary.
方法#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))
The original dictionary is : {‘Gfg’: 5, ‘is’: 8, ‘Best’: 10, ‘for’: 8, ‘Geeks’: 9}
The updated dictionary: {‘Gfg’: 10, ‘is’: 8, ‘Best’: 17, ‘for’: 8, ‘Geeks’: 9}
方法#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))
The original dictionary is : {‘Gfg’: 5, ‘is’: 8, ‘Best’: 10, ‘for’: 8, ‘Geeks’: 9}
The updated dictionary: {‘Gfg’: 10, ‘is’: 8, ‘Best’: 17, ‘for’: 8, ‘Geeks’: 9}