python - 在Python中合并多个列表中的字典

标签 python dictionary

我有三个列表,里面有多个字典。

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/

相关文章:

python - NetworkX 和 Matplotlib - 文本标签错位

java - 如何让 ComputeIfPresent 在 Map 中与 Map 一起工作?

Python 字典键作为一组数字

javascript - 打破 map

python - 如何在不替换的情况下添加到python字典

C++ map 容器

python - 将 cookie 字符串转换为 Python 字典

python - 在测试之间自动删除 MEDIA_ROOT

python - Python Redis和celery客户端过多,每次执行时都会出现不同的错误|任务使用pymsql连接到MySQL

python - [a-zA-Z] Python 正则表达式模式可以匹配和替换非 ASCII Unicode 字符吗?