# 将列表中的字典相同元素合并,并输出新的字典
v = [{'id': 1, 'teacher_name': ' 李', 'class_name': '3班'},
{'id': 1, 'teacher_name': ' 李', 'class_name': '2班'},
{'id': 2, 'teacher_name': '赵日天', 'class_name': '3班'},
{'id': 3, 'teacher_name': '日地', 'class_name': '3班'},
{'id': 3, 'teacher_name': '日地', 'class_name': '1班'}]
new_dict = {}
for i in v:
if i['id'] not in new_dict:
new_dict[i['id']] = str(i['teacher_name']) + ',' + str(i['class_name'])
else:
list1 = new_dict[i['id']].strip().split(',')
# print(list1)
new_dict[i['id']] = str(i['teacher_name']) + ',' + str(list1[1])+str(i['class_name'])
# print(new_dict)
new_list = []
for x, y in new_dict.items():
v1 = y.split(',')
new_list.append({'id':x,'teacher_name':str(v1[0]),'class_name':str(v1[1])})
for i in new_list:
print(i)
列表中的相同字典元素合并,再输出字典
最新推荐文章于 2023-03-20 17:05:05 发布