python3 處理列表巢狀字典去重
阿新 • • 發佈:2020-07-17
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)) """ 整體思路就是將需要合併的欄位改為列表 再通過主鍵的方式校驗重複,如果主鍵重複就將需要合併的欄位新增到新的列表中。 不重複則直接返回並將自己新增到一個新列表中 """