How to convert a list with key value pairs to dictionary
I am assuming that your order is always the same, i.e., in groups of 4. The idea is to split the strings using :
and then create key/value pairs and use nested for loops. The .strip()
is to get rid of whitespace
lst = ['name: test1', 'email: [email protected]', 'role: test', 'description: test',
'name: test2', 'email: [email protected]', 'role: test2', 'description: test2',
'name: test3', 'email: [email protected]', 'role: test3', 'description: test3']
answer = []
for i in range(0, len(lst), 4):
dic = {}
for j in lst[i:i+4]:
dic[j.split(':')[0]] = j.split(':')[1].strip()
answer.append(dic)
# [{'name': 'test1', 'email': '[email protected]', 'role': 'test', 'description': 'test'},
# {'name': 'test2', 'email': '[email protected]', 'role': 'test2', 'description': 'test2'},
# {'name': 'test3', 'email': '[email protected]', 'role': 'test3', 'description': 'test3'}]
A list comprehension would look like
answer = [{j.split(':')[0]:j.split(':')[1].strip() for j in lst[i:i+4]} for i in range(0, len(lst), 4)]
Without having to know the number of keys each dict has in advance, you can iterate through the list, split each string into a key and a value by ': '
, appending a new dict to the list if the key is already in the last dict, and keep adding the value to the last dict by the key:
output = []
for key_value in lst:
key, value = key_value.split(': ', 1)
if not output or key in output[-1]:
output.append({})
output[-1][key] = value
so that given your sample list stored in lst
, output
would become:
[{'name': 'test1',
'email': '[email protected]',
'role': 'test',
'description': 'test'},
{'name': 'test2',
'email': '[email protected]',
'role': 'test2',
'description': 'test2'},
{'name': 'test3',
'email': '[email protected]',
'role': 'test3',
'description': 'test3'}]