def list_dict(dictlist):
def function(date):
return date['ip']
dictlist_new = []
for list_dict in dictlist:
list_dict['backPath'] = [list_dict['backPath']]
dictlist_new.append(list_dict)
resource_new = []
num = 0
dictlist_new.sort(key=function)
for dictlist in dictlist_new:
if num == 0:
resource_new.append(dictlist)
else:
if resource_new[0]['ip'] != dictlist['ip']:
old = resource_new[0]
del resource_new[0]
resource_new.append(dictlist)
resource_new.append(old)
elif resource_new[0]['ip'] == dictlist['ip']:
resource_new[0]['backPath'].append(dictlist['backPath'][0])
num += 1
return resource_new
resource_list = [
{"ip": "10.23.13.8", "backPath": '/usr/sap/1111', "user": "root", "PASSWD": "1212121"},
{"ip": "10.23.13.8", "backPath": "/usr/sap/1112", "user": "root", "PASSWD": "1212121"},
{"ip": "10.23.13.9", "backPath": "/usr/sap/1111", "user": "root", "PASSWD": "1212121"},
{"ip": "10.23.13.10", "backPath": "/usr/sap/1111", "user": "root", "PASSWD": "1212121"},
{"ip": "10.23.13.8", "backPath": "/usr/sap/1113", "user": "root", "PASSWD": "1212121"}
]
print(list_dict(resource_list))
"""
整体思路就是将需要合并的字段改为列表
再通过主键的方式校验重复,如果主键重复就将需要合并的字段添加到新的列表中。
不重复则直接返回并将自己添加到一个新列表中
"""