Reputation: 74
I am trying to combine two elements in a list to form a nested list in the original list. I am stuck. I can iterate through the list and get the specific elements, but I'm not sure how to create a nested list with them in the original list.
This is the original list.
[
{'LIN02': 'GS', 'LIN04': 'MF', 'LIN03': 'BOSEF2', 'LIN06': 'ST', 'LIN05': 'BOSTIK', 'LIN07': 'BOSEF2', 'id': 'LIN'},
{'PID02': 'TRN', 'PID01': 'F', 'PID05': 'EFA+ 28 OZ TUBE ADHESIVE', 'id': 'PID'},
{'PID02': 'MAC', 'PID01': 'F', 'PID05': 'INSADH', 'id': 'PID'},
{'MEA04': 'EA', 'MEA03': '1.000', 'MEA02': 'SU', 'id': 'MEA'}
]
I would like it to output like this.
[
{'LIN02': 'GS', 'LIN04': 'MF', 'LIN03': 'BOSEF2', 'LIN06': 'ST', 'LIN05': 'BOSTIK', 'LIN07': 'BOSEF2', 'id': 'LIN'},
[
{'PID02': 'TRN', 'PID01': 'F', 'PID05': 'EFA+ 28 OZ TUBE ADHESIVE', 'id': 'PID'},
{'PID02': 'MAC', 'PID01': 'F', 'PID05': 'INSADH', 'id': 'PID'}
],
{'MEA04': 'EA', 'MEA03': '1.000', 'MEA02': 'SU', 'id': 'MEA'}
]
This is what I have so far.
loop_2000 = ['LIN02': 'GS', 'LIN04': 'MF', 'LIN03': 'BOSEF2', 'LIN06': 'ST', 'LIN05': 'BOSTIK', 'LIN07': 'BOSEF2', 'id': 'LIN'}, {'PID02': 'TRN', 'PID01': 'F', 'PID05': 'EFA+ 28 OZ TUBE ADHESIVE', 'id': 'PID'}, {'PID02': 'MAC', 'PID01': 'F', 'PID05': 'INSADH', 'id': 'PID'}, {'MEA04': 'EA', 'MEA03': '1.000', 'MEA02': 'SU', 'id': 'MEA'}]
for n in enumerate(loop_2000):
for line in enumerate(n[1]):
if line[1]["id"] == "PID":
print(line)
Not sure if this is the most efficient way to solve this, but I found a work around.
pid_list = []
pid_index = []
for line in enumerate(loop_2000):
if line[1]["id"] == "PID":
pid_index.append(line[0])
pid_list.append(line[1])
loop_2000.insert(line[0], pid_list)
del loop_2000[pid_index[0]: pid_index[0] + 2]
Upvotes: 0
Views: 72
Reputation: 136
Try this.
list2 = []
list2 = [element for element in list1 if element['id'] !='PID']
list2.append([element for element in list1 if element['id'] =='PID'])
Upvotes: 1