使用字典列表中的值更新字典的Python程序
给定字典和字典列表,用字典列表值更新字典。
Input : test_dict = {“Gfg” : 2, “is” : 1, “Best” : 3}, dict_list = [{‘for’ : 3, ‘all’ : 7}, {‘and’ : 1, ‘CS’ : 9}]
Output : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7, ‘and’: 1, ‘CS’: 9}
Explanation : All dictionary keys updated in single dictionary.
Input : test_dict = {“Gfg” : 2, “is” : 1, “Best” : 3}, dict_list = [{‘for’ : 3, ‘all’ : 7}]
Output : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7}
Explanation : All dictionary keys updated in single dictionary.
方法 #1:使用update() + 循环
在这里,我们遍历循环中的所有元素,并执行更新以将字典中的所有键更新为原始字典。
Python3
# Python3 code to demonstrate working of
# Update dictionary with dictionary list
# Using update() + loop
# initializing dictionary
test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing dictionary list
dict_list = [{'for' : 3, 'all' : 7}, {'geeks' : 10}, {'and' : 1, 'CS' : 9}]
for dicts in dict_list:
# updating using update()
test_dict.update(dicts)
# printing result
print("The updated dictionary : " + str(test_dict))
Python3
# Python3 code to demonstrate working of
# Update dictionary with dictionary list
# Using ChainMap + ** operator
from collections import ChainMap
# initializing dictionary
test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing dictionary list
dict_list = [{'for' : 3, 'all' : 7}, {'geeks' : 10}, {'and' : 1, 'CS' : 9}]
# ** operator extracts keys and re initiates.
# ChainMap is used to merge dictionary list
res = {**test_dict, **dict(ChainMap(*dict_list))}
# printing result
print("The updated dictionary : " + str(res))
输出:
The original dictionary is : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3}
The updated dictionary : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7, ‘geeks’: 10, ‘and’: 1, ‘CS’: 9}
方法 #2:使用ChainMap + **运算符
在此,我们使用 ChainMap 执行将所有列表字典合并为 1 的任务,并使用 **运算符将目标字典合并到合并字典。
蟒蛇3
# Python3 code to demonstrate working of
# Update dictionary with dictionary list
# Using ChainMap + ** operator
from collections import ChainMap
# initializing dictionary
test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing dictionary list
dict_list = [{'for' : 3, 'all' : 7}, {'geeks' : 10}, {'and' : 1, 'CS' : 9}]
# ** operator extracts keys and re initiates.
# ChainMap is used to merge dictionary list
res = {**test_dict, **dict(ChainMap(*dict_list))}
# printing result
print("The updated dictionary : " + str(res))
输出:
The original dictionary is : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3}
The updated dictionary : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7, ‘geeks’: 10, ‘and’: 1, ‘CS’: 9}