简体   繁体   中英

How do I split list of dict in Python?

lis_dict = [
   {item: "some item"}, 
   {quantity: 2}, 
   {id: 10}, 
   {quantity: 2}, 
   {id: 11}, 
   {quantity: 2}, 
   {quantity: 2}, 
   {id: 12}
]

I have above list of dict , which I would like to split into a sub-list.

result  = [
   [{item: "some item"}, {quantity: 2}, {id: 10}],
   [{quantity: 2}, {id: 11}],
   [{quantity: 2}, {quantity: 2}, {id: 12}]
]

The question asks to split the list by "id" into a nested list.

Input:

lis_dict
[{'item': 'some item'},
 {'quantity': 2},
 {'id': 10},
 {'quantity': 2},
 {'id': 11},
 {'quantity': 2},
 {'quantity': 2},
 {'id': 12}]

Code:

result = []
s = 0
for i,j in enumerate(lis_dict):
    if ("id" in j.keys()):
        result.append(lis_dict[s:i+1])
        s = i+1

Prints:

[[{'item': 'some item'}, {'quantity': 2}, {'id': 10}],
 [{'quantity': 2}, {'id': 11}],
 [{'quantity': 2}, {'quantity': 2}, {'id': 12}]]

A more general approach might be the following (in which you could add more dictionaries in a sublist):

lis_dict = [{'item': 'some item'},
 {'quantity': 2},
 {'id': 10},
 {'quantity': 2},
 {'item': 'some item'},
 {'id': 11},
 {'quantity': 2},
 {'quantity': 2},
 {'id': 12}]

result = []
sublist = []
for d in lis_dict:
    sublist.append(d)
    if d.get("id"):
        result.append(sublist)
        sublist = []

print(result)

# [[{'item': 'some item'}, {'quantity': 2}, {'id': 10}], [{'quantity': 2}, 
# {'item': 'some item'}, {'id': 11}], [{'quantity': 2}, {'quantity': 2}, {'id': 12}]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM