Python – 用其他字典更新字典
有时,在使用Python字典时,我们可能会遇到需要使用字典的其他键执行字典更新的问题。这可以在我们需要将某些记录添加到先前捕获的记录的域中具有应用程序。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的蛮力方式。在此,我们检查其他字典中的键,并将项目添加到新字典中。
# Python3 code to demonstrate working of
# Update dictionary with other dictionary
# Using loop
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'best' : 2, 'for' : 4, 'geeks' : 6}
test_dict2 = {'for' : 3, 'geeks' : 5}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Update dictionary with other dictionary
# Using loop
for key in test_dict1:
if key in test_dict2:
test_dict1[key] = test_dict2[key]
# printing result
print("The updated dictionary is : " + str(test_dict1))
输出 :
The original dictionary 1 is : {‘best’: 2, ‘for’: 4, ‘gfg’: 1, ‘geeks’: 6}
The original dictionary 2 is : {‘for’: 3, ‘geeks’: 5}
The updated dictionary is : {‘best’: 2, ‘for’: 3, ‘gfg’: 1, ‘geeks’: 5}
方法#2:使用字典理解
这是可以执行此任务的另一种方式。在此,我们迭代字典并使用理解在单行中执行更新。
# Python3 code to demonstrate working of
# Update dictionary with other dictionary
# Using dictionary comprehension
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'best' : 2, 'for' : 4, 'geeks' : 6}
test_dict2 = {'for' : 3, 'geeks' : 5}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Update dictionary with other dictionary
# Using dictionary comprehension
res = {key : test_dict2.get(key, val) for key, val in test_dict1.items()}
# printing result
print("The updated dictionary is : " + str(res))
输出 :
The original dictionary 1 is : {‘best’: 2, ‘for’: 4, ‘gfg’: 1, ‘geeks’: 6}
The original dictionary 2 is : {‘for’: 3, ‘geeks’: 5}
The updated dictionary is : {‘best’: 2, ‘for’: 3, ‘gfg’: 1, ‘geeks’: 5}