2016-06-11 4 views
2

У меня есть три списка с несколькими словарями внутри.Объединить словари из нескольких списков в Python

list1 = [{'question': u'Fan offline information can be found on what Screen under General Menu? '}, {'question': u'What is the tool for F5 BIGIP to get packet traces. '}, {'question': u'On a HTTP Health Monitor configuration. If Receive string and Disabling string matched and Reverse is enabled. What would be the status of pool members?'}] 
list2 = [{'answer': u'SysteminfoScreen'}, {'answer': u'qkview'}, {'answer': u'Offline'}] 
list3 = [{'correct_answer': u'SysteminfoScreen'}, {'correct_answer': u'TCP Dump'}, {'correct_answer': u'Disabled'}] 

Как я могу объединить эти три списка в результате, подобные этому?

[{'question': u'What is the tool for F5 BIGIP to get packet traces. ', 'answer': u'qkview', 'correct_answer': u'TCP Dump'}] 

Другой вариант, если вышеуказанная проблема не достижима

list1 = ['Fan offline information can be found on what Screen under General Menu? ', 'What is the tool for F5 BIGIP to get packet traces. ', 'On a HTTP Health Monitor configuration. If Receive string and Disabling string matched and Reverse is enabled. What would be the status of pool members?'] 
list2 = ['SysteminfoScreen', 'qkview', 'Offline'] 
list3 = ['SysteminfoScreen', 'TCP Dump', 'Disabled'] 

Слияние трех в тот же результат:

[{'question': u'What is the tool for F5 BIGIP to get packet traces. ', 'answer': u'qkview', 'correct_answer': u'TCP Dump'}] 

PS

Я использую питона 2.7.10

ответ

2

zip словарные статьи в списках. Преобразование словарей в список ключ-значение tuples, объединить списки с помощью +, а затем преобразовать слитый список обратно в словарь:

[dict(i.items()+j.items()+k.items()) for i, j, k in zip(list1, list2, list3)] 

В Python 3.x, вам нужно будет позвонить list на dict_items :

[dict(list(i.items())+list(j.items())+list(k.items())) for i,j,k in zip(list1, list2, list3)] 

Результат:

[{'answer': 'SysteminfoScreen', 
    'question': 'Fan offline information can be found on what Screen under General Menu? ', 
    'correct_answer': 'SysteminfoScreen'}, 
{'answer': 'qkview', 
    'question': 'What is the tool for F5 BIGIP to get packet traces. ', 
    'correct_answer': 'TCP Dump'}, 
{'answer': 'Offline', 
    'question': 'On a HTTP Health Monitor configuration. If Receive string and Disabling string matched and Reverse is enabled. What would be the status of pool members?', 
    'correct_answer': 'Disabled'}] 

словарь элементы не упорядочены, поэтому каждый словарь может не заходите в Question-Answer-CorrectAnswer. Заказ может быть другим.

+0

AttributeError: объект 'str' не имеет атрибутов 'items' является результатом вашего кода, кстати, я использую python2 –

+0

@DeanChristianArmada Этот ответ предполагает проблему со списком слов, а не список-словаря, которые вы пытаетесь. – ppperry

+0

@DeanChristianArmada Этот подход использует список словарей –

2

Просто цикл его, сохранить его простым и читаемым:

res = [] # keep results 

for vals in zip(list1, list2, list3): # grab each entry 
    d = {}        # tmp dictionary 
    for subv in vals: d.update(subd) # update tmp dictionary 
    res.append(d)      # add to result 

Для вашего входа, этот выход:

[{'answer': 'SysteminfoScreen', 
    'correct_answer': 'SysteminfoScreen', 
    'question': 'Fan offline information can be found on what Screen under General Menu? '}, 
{'answer': 'qkview', 
    'correct_answer': 'TCP Dump', 
    'question': 'What is the tool for F5 BIGIP to get packet traces. '}, 
{'answer': 'Offline', 
    'correct_answer': 'Disabled', 
    'question': 'On a HTTP Health Monitor configuration. If Receive string and Disabling string matched and Reverse is enabled. What would be the status of pool members?'}] 
1

Я думаю, что следующие выглядит довольно хорошо для второй конфигурации вы Offerred. Мне понадобилось бы какое-то переменное переименование, хотя, на мой взгляд, было бы яснее.

[dict(question=a, answer=b, correct_answer=c) for (a, b, c) in zip(list1, list2, list3)] 

Примечание:

выше решение также может быть записана в виде

[{'question': a, 'answer': b, 'correct_answer': c} for (a, b, c) in zip(list1, list2, list3)] 

, но я думаю, что мой основной ответ выглядит чище (меньше серии скобок).

+0

Вау, это отличный ответ! –

Смежные вопросы