list1 = [{'id': 1, 'data1': 'Chris', 'data2': ['Salt', 'Texas']},
{'id': 2, 'data1': 'Smith', 'data2': ['Melbourne', 'Victoria', 'Sydney']}]
list2 = [{'id': 1, 'data1': ['Royne','Nick'], 'data2': 'US'},
{'id': 2, 'data1': ['Harry','Jorge','Marie'], 'data2': 'Australia'}]
我想合并这两个列表并获取:
merged_list = [{'id': 1, 'data1': ['Chris','Royne','Nick']', 'data2': ['US','Salt', 'Texas']},
{'id': 2, 'data1': ['Smith','Harry','Jorge','Marie'], 'data2': ['Australia','Melbourne', 'Victoria', 'Sydney']}]
答案 0 :(得分:0)
def merge_dicts(list1, list2):
merged_list = []
for i, (d1, d2) in enumerate(zip(list1, list2)):
merged_list.append({})
for d in [d1, d2]:
for k, v in d.items():
if k in merged_list[i]:
if v not in merged_list[i][k]:
if isinstance(v, list):
merged_list[i][k].extend(v)
else:
merged_list[i][k].append(v)
else:
if isinstance(v, list):
merged_list[i][k] = v
else:
merged_list[i][k] = [v]
for k, v in merged_list[i].items():
if len(v) == 1:
merged_list[i][k] = v[0]
else:
merged_list[i][k] = v
return merged_list
>>> merge_dicts(list1, list2)
[{'id': 1, 'data1': ['Chris', 'Royne', 'Nick'], 'data2': ['Salt', 'Texas', 'US']}, {'id': 2, 'data1': ['Smith', 'Harry', 'Jorge', 'Marie'], 'data2': ['Melbourne', 'Victoria', 'Sydney', 'Australia']}]