Python - 合并具有重复键的字典列表
给定两个可能有重复键的字典列表,编写一个Python程序来执行合并。
例子:
Input : test_list1 = [{“gfg” : 1, “best” : 4}, {“geeks” : 10, “good” : 15}, {“love” : “gfg”}], test_list2 = [{“gfg” : 6}, {“better” : 3, “for” : 10, “geeks” : 1}, {“gfg” : 10}]
Output : [{‘gfg’: 1, ‘best’: 4}, {‘geeks’: 10, ‘good’: 15, ‘better’: 3, ‘for’: 10}, {‘love’: ‘gfg’, ‘gfg’: 10}]
Explanation : gfg while merging retains value of 1, and “best” is added to dictionary as key from other list’s 1st dictionary ( same index ).
Input : test_list1 = [{“gfg” : 1, “best” : 4}, {“love” : “gfg”}], test_list2 = [{“gfg” : 6}, {“gfg” : 10}]
Output : [{‘gfg’: 1, ‘best’: 4}, {‘love’: ‘gfg’, ‘gfg’: 10}]
Explanation : gfg while merging retains value of 1, and “best” is added to dictionary as key from other list’s 1st dictionary ( same index ).
方法:使用循环+键()
在此我们根据所有不重复的键重建键值对,使用 in运算符检查并使用 keys() 提取键。
Python3
# Python3 code to demonstrate working of
# Merge Dictionaries List with duplicate Keys
# Using loop + keys()
# initializing lists
test_list1 = [{"gfg": 1, "best": 4}, {"geeks": 10, "good": 15},
{"love": "gfg"}]
test_list2 = [{"gfg": 6}, {"better": 3, "for": 10, "geeks": 1},
{"gfg": 10}]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
for idx in range(0, len(test_list1)):
# getting keys of corresponding index
id_keys = list(test_list1[idx].keys())
for key in test_list2[idx]:
# checking for keys presence
if key not in id_keys:
test_list1[idx][key] = test_list2[idx][key]
# printing result
print("The Merged Dictionary list : " + str(test_list1))
输出:
The original list 1 is : [{‘gfg’: 1, ‘best’: 4}, {‘geeks’: 10, ‘good’: 15}, {‘love’: ‘gfg’}]
The original list 2 is : [{‘gfg’: 6}, {‘better’: 3, ‘for’: 10, ‘geeks’: 1}, {‘gfg’: 10}]
The Merged Dictionary list : [{‘gfg’: 1, ‘best’: 4}, {‘geeks’: 10, ‘good’: 15, ‘better’: 3, ‘for’: 10}, {‘love’: ‘gfg’, ‘gfg’: 10}]