[英]how to create a list of values from one key-value pair based on the value of another k-v pair from a list of dictionaries with two key-value pairs
[英]Python TypeError: Mapping the values of two lists into key-value pairs in a new one container list
我有两个列表/数组titles
和descriptions
,如下所示:
titles = ['title1', 'title2', 'title3']
descriptions = ['description1', 'description2', 'description3']
我需要制作一个包含两者的列表/数组topic
,作为字典/对象键值对,如下所示:
topics [
{
'title': 'title1',
'description': 'description1'
},
{
'title': 'title2',
'description': 'description2'
},
{
'title': 'title3',
'description': 'description3'
}
]
我试图像在PHP或JS中那样做:
titles = ['title1', 'title2', 'title3']
descriptions = ['description1', 'description2', 'description3']
topics = []
for i in range(len(titles)):
topics[i]['title'] = titles[i]
topics[i]['description'] = descriptions[i]
但是我得到了这个错误:
topic topics[i]['title'] = titles[i]
TypeError:“ NoneType”对象没有属性“ getitem ”
那么,我该如何在python中做这些事情呢?
您可以使用zip
进行列表理解:
[{'title': x, 'description': y} for x, y in zip(titles, descriptions)]
范例 :
titles = ['title1', 'title2', 'title3']
descriptions = ['description1', 'description2', 'description3']
print([{'title': x, 'description': y} for x, y in zip(titles, descriptions)])
# [{'title': 'title1', 'description': 'description1'},
# {'title': 'title2', 'description': 'description2'},
# {'title': 'title3', 'description': 'description3'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.