Dean Christian Armada Dean Christian Armada - 6 months ago 13
Python Question

Merge dictionaries from multiple lists in Python

I have three list with multiple dictionaries inside.

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


How can I combine this three list as a result similar to this?

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


Another option if above problem is not achievable

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


Merging the three into the same result of:

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


PS

I am using python 2.7.10

Answer

zip the dictionary items in the lists. Transform the dictionaries into a list of key-value tuples, merge the lists using +, then transform the merged list back into a dictionary:

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

In python 3.x, you will need to call list on the dict_items:

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

Result:

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

Dictionary items are not ordered, so each dictionary may not go in Question-Answer-CorrectAnswer order. Order may be different.