How to convert a list with key value pairs to dictionary

Viewed 11958

I'd like to iterate over this list

['name: test1', 'email: test1@gmail.com', 'role: test', 'description: test', 'name: test2', 'email: test2@gmail.com', 'role: test2', 'description: test2', 'name: test3', 'email: test3@gmail.com', 'role: test3', 'description: test3']

and return a list of dictionaries for each group. E.g.

[{name: 'test', email:'test@gmail.com', role:'test', description:'test'}, {name: 'test2', email:'test2@gmail.com', role:'test2', description:'test2'}]

I've tried splitting the list by , (comma) and searching it for 'name:'. I can return one field such as name, but am struggling to link to to the email, role, etc.

Thanks for any help in advance.

5 Answers

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': 'test1@gmail.com',
  'role': 'test',
  'description': 'test'},
 {'name': 'test2',
  'email': 'test2@gmail.com',
  'role': 'test2',
  'description': 'test2'},
 {'name': 'test3',
  'email': 'test3@gmail.com',
  'role': 'test3',
  'description': 'test3'}]

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: test1@gmail.com', 'role: test', 'description: test', 
       'name: test2', 'email: test2@gmail.com', 'role: test2', 'description: test2', 
       'name: test3', 'email: test3@gmail.com', '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': 'test1@gmail.com',  'role': 'test',  'description': 'test'},
    #  {'name': 'test2',  'email': 'test2@gmail.com',  'role': 'test2',  'description': 'test2'},
    #  {'name': 'test3',  'email': 'test3@gmail.com',  '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)]

You could do :

dictionary = dict()
all_dictionaries = []
for index , value  in  [x.split(": ") for x in A] :
     if index in dictionary :
         all_dictionaries .append(dictionary )
         dictionary = dict()
     else :
       dictionary [index] = value
all_dictonaries.append(dictionary)

If the form of the data in the list is guaranteed to always be the way it is in the question's example, then you can do this:

L = ['name: test1', 'email: test1@gmail.com', 'role: test', 'description: test', 'name: test2', 'email: test2@gmail.com', 'role: test2', 'description: test2', 'name: test3', 'email: test3@gmail.com', 'role: test3', 'description: test3']

A = []

for i in range(0, len(L), 4):
  D = {}
  for p in L[i:i + 4]:
    k, v = map(str.strip, p.split(':'))
    D[k] = v
  A.append(D)

from pprint import pprint
pprint(A)

Output:

[{'description': 'test',
  'email': 'test1@gmail.com',
  'name': 'test1',
  'role': 'test'},
 {'description': 'test2',
  'email': 'test2@gmail.com',
  'name': 'test2',
  'role': 'test2'},
 {'description': 'test3',
  'email': 'test3@gmail.com',
  'name': 'test3',
  'role': 'test3'}]

This solution assumes the size of each group is exactly 4

l = ['name: test1', 'email: test1@gmail.com', 'role: test', 'description: test', 
     'name: test2', 'email: test2@gmail.com', 'role: test2', 'description: test2',
     'name: test3', 'email: test3@gmail.com', 'role: test3', 'description: test3']

output = [dict(s.split(": ") for s in l[i:i+4]) for i in range(0, len(l), 4)]
Related