Как преобразовать список с парами ключ-значение в словарь - PullRequest
1 голос
/ 08 июня 2019

Я бы хотел перебрать этот список

['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']

и вернуть список словарей для каждой группы.Например,

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

Я попытался разделить список (запятая) и найти его по имени:.Я могу вернуть одно поле, например, имя, но изо всех сил пытаюсь дать ссылку на адрес электронной почты, роль и т. Д.

Спасибо за любую помощь заранее.

Ответы [ 5 ]

3 голосов
/ 08 июня 2019

Не зная заранее, сколько ключей имеет каждый диктовку, вы можете перебирать список, разбивать каждую строку на ключ и значение на ': ', добавляя новый диктат в список, если ключ уже существуетв последнем dict и продолжайте добавлять значение к последнему dict с помощью ключа:

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

, так что, учитывая ваш список образцов, хранящийся в lst, output станет:

[{'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'}]
2 голосов
/ 08 июня 2019

Если форма данных в списке гарантированно всегда будет такой же, как в примере вопроса, то вы можете сделать это:

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)

Вывод:

[{'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'}]
2 голосов
/ 08 июня 2019

Я предполагаю , что ваш порядок всегда одинаков, то есть в группах по 4. Идея состоит в том, чтобы разбить строки, используя :, а затем создать пары ключ / значение и использовать вложенные для циклов , .strip() - избавиться от пробела

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'}]

Понимание списка будет выглядеть как

answer = [{j.split(':')[0]:j.split(':')[1].strip() for j in lst[i:i+4]} for i in range(0, len(lst), 4)]
1 голос
/ 08 июня 2019

В этом решении предполагается, что размер каждой группы равен 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)]
1 голос
/ 08 июня 2019

Вы можете сделать:

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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...