简体   繁体   中英

Python TypeError: Mapping the values of two lists into key-value pairs in a new one container list

I've two lists/arrays titles and descriptions as below:

 titles = ['title1', 'title2', 'title3']
 descriptions = ['description1', 'description2', 'description3']

I need to make one list/array topic containing both of them as dictionaries/objects key-value pairs as below:

topics [
   {
     'title': 'title1',
     'description': 'description1'
   },
   {
     'title': 'title2',
     'description': 'description2'
   },
   {
     'title': 'title3',
     'description': 'description3'
   }
]

I've tried to do that like in PHP or 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]

But I got that error:

topics[i]['title'] = titles[i] TypeError: 'NoneType' object has no attribute ' getitem '

So how shoud I do that stuff in python?

You can do a list-comprehension using zip :

[{'title': x, 'description': y} for x, y in zip(titles, descriptions)]

Example :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM