You need to decide, in code, how to group the strings into dictionaries. Perhaps there are always 2 elements each, or there is always a Name
entry, or you simply need to create a new dictionary each time a key has been seen before.
If there are always N elements per dictionary, then iterate in chunks of that size:
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
results = [
dict(tuple(map(str.strip, entry.split(': '))) for entry in per_dict)
for per_dict in chunks(inputlist, 2)
]
Demo:
>>> from pprint import pprint
>>> inputlist = ['Name: volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index: 24', 'Name: volume_xx111', 'Index: 3', 'Name: volume_xx11541', 'Index: 4', 'Name: Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index: 6']
>>> def chunks(l, n):
... """Yield successive n-sized chunks from l."""
... for i in range(0, len(l), n):
... yield l[i:i + n]
...
>>> [
... dict(tuple(map(str.strip, entry.split(': '))) for entry in per_dict)
... for per_dict in chunks(inputlist, 2)
... ]
[{'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index': '24'}, {'Name': 'volume_xx111', 'Index': '3'}, {'Name': 'volume_xx11541', 'Index': '4'}, {'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index': '6'}]
>>> pprint(_)
[{'Index': '24', 'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37'},
{'Index': '3', 'Name': 'volume_xx111'},
{'Index': '4', 'Name': 'volume_xx11541'},
{'Index': '6',
'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10'}]
If seeing a key repeat is the better approach, then start with a list result
containing an empty dictionary; you add key-value pairs to result[-1]
. Then process your strings one by one, splitting each on the ':'
character to create a key and value pair. If the key already is found in the most recent dictionary, start a new empty one:
results = [{}]
for entry in inputlist:
key, value = map(str.strip, entry.split(':')) # removing surrounding whitespace
if key in results[-1]:
# start a new dictionary
results.append({})
results[-1][key] = value
By checking for the key
existing, it no longer matters if a Name
and Index
entry got swapped.
Demo:
>>> results = [{}]
>>> for entry in inputlist:
... key, value = map(str.strip, entry.split(':')) # removing surrounding whitespace
... if key in results[-1]:
... # start a new dictionary
... results.append({})
... results[-1][key] = value
...
>>> pprint(results)
[{'Index': '24', 'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37'},
{'Index': '3', 'Name': 'volume_xx111'},
{'Index': '4', 'Name': 'volume_xx11541'},
{'Index': '6',
'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10'}]