可以通过以下步骤实现:
以下是一个示例代码:
def merge_dicts(dict_list1, dict_list2):
merged_dict_list = []
# 遍历第一个字典列表,将每个字典中的键值对逐个添加到结果字典列表中
for dictionary in dict_list1:
merged_dict_list.append(dictionary)
# 遍历第二个字典列表,对于每个字典中的键值对,如果键已存在于结果字典列表中,则更新对应的值;如果键不存在,则将该键值对添加到结果字典列表中
for dictionary in dict_list2:
for key, value in dictionary.items():
found = False
for merged_dict in merged_dict_list:
if key in merged_dict:
merged_dict[key] = value
found = True
break
if not found:
merged_dict_list.append({key: value})
return merged_dict_list
这个函数接受两个字典列表作为参数,返回合并后的字典列表。你可以调用这个函数来合并两个字典列表,例如:
dict_list1 = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
dict_list2 = [{'name': 'Charlie', 'gender': 'male'}, {'name': 'Alice', 'age': 26}]
merged_dict_list = merge_dicts(dict_list1, dict_list2)
print(merged_dict_list)
输出结果为:
[{'name': 'Alice', 'age': 26}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'gender': 'male'}]
这个例子中,我们将两个字典列表合并到一个字典列表中,其中第一个字典列表包含两个字典,第二个字典列表也包含两个字典。合并后的结果字典列表中包含三个字典,其中第一个字典的键"name"在两个字典列表中都存在,因此更新了值;第二个字典的键"name"在第一个字典列表中存在,因此更新了值;第三个字典的键"name"在第一个字典列表中不存在,因此添加了该键值对。
领取专属 10元无门槛券
手把手带您无忧上云