我有三个列表,里面有多个字典。
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'}]
附注
我使用的是 python 2.7.10
最佳答案
zip
列表中的字典项目。将字典转换为键值元组列表,使用 +
合并列表,然后将合并的列表转换回字典:
[dict(i.items()+j.items()+k.items()) for i, j, k in zip(list1, list2, list3)]
在 python 3.x 中,您需要在 dict_items
上调用 list
:
[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'}]
字典项目没有排序,因此每个字典可能不会按问题-答案-正确答案的顺序排列。顺序可能不同。
关于python - 在Python中合并多个列表中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37759059/