-2

I want to split the following list into several lists from the key-value of 'time':'0.00'.

lst = [
       {'time':'0.00', 'co2':'18.00'}, {'time':'1.00', 'co2':'28.00'},
       {'time':'0.00', 'co2':'38.00'}, {'time':'4.00', 'co2':'12.00'},
       {'time':'0.00', 'co2':'20.00'}, {'time':'3.00', 'co2':'18.00'}
       ]

The result would be:

lst_1 = [{'time':'0.00', 'co2':'18.00'}, {'time':'1.00', 'co2':'28.00'}]
lst_2 = [{'time':'0.00', 'co2':'38.00'}, {'time':'4.00', 'co2':'12.00'}]
lst_3 = [{'time':'0.00', 'co2':'20.00'}, {'time':'3.00', 'co2':'18.00'}]

Any help would be appreciated.

Ali
  • 115
  • 5

1 Answers1

0

It is hard to create new variables dynamically in Python and often is not needed (see: stackoverflow).

I suggest you to create a dict this way:

lst = [
   {'time':'0.00', 'co2':'18.00'}, {'time':'1.00', 'co2':'28.00'},
   {'time':'0.00', 'co2':'38.00'}, {'time':'4.00', 'co2':'12.00'},
   {'time':'0.00', 'co2':'20.00'}, {'time':'3.00', 'co2':'18.00'}
   ]

dict_of_lists = {}

for counter in range(0, len(lst), 2):
    dict_of_lists[f"lst_{(counter + 1) // 2 + 1}"] = lst[counter: counter + 2]

print(dict_of_lists)

Result:

{'lst_1': [{'time': '0.00', 'co2': '18.00'}, {'time': '1.00', 'co2': '28.00'}],
 'lst_2': [{'time': '0.00', 'co2': '38.00'}, {'time': '4.00', 'co2': '12.00'}],
 'lst_3': [{'time': '0.00', 'co2': '20.00'}, {'time': '3.00', 'co2': '18.00'}]}
artemonsh
  • 113
  • 3
  • 13