bob90937 bob90937 - 1 month ago 14
JSON Question

how to combine three list into one list by specious format such as dictionary or JSON ? Python

I have three lists:

imglist=['1.jpg', '12.jpg']
classlist=['class1', 'class5']
sentencelist=['Good for health.', 'Good luck.']


how to combine the list into following format?

[ ['1.jpg','class1','Good for health.'],
['12.jpg','class5','Good luck.']]


or if u know how to combine the lists as dictionary or JSON format ? such as

[{'img':'1.jpg','class':'class1','sentence':'Good for health.'},
{'img':'12.jpg','class':'class5','sentence':'Good luck'}]

Answer

Use zip() to combine the list as:

>>> imglist=['1.jpg', '12.jpg']
>>> classlist=['class1', 'class5']
>>> sentencelist=['Good for health.', 'Good luck.']

# combining list
>>> zip(imglist, classlist, sentencelist)
[('1.jpg', 'class1', 'Good for health.'), ('12.jpg', 'class5', 'Good luck.')]

For converting it to dict of your format, use zip with list comprehension as:

>>> key_list = ["img", "class", "sentence"]
>>> my_zipped_list = zip(imglist, classlist, sentencelist)  # same list as above example

>>> [dict(zip(key_list, zipped_element)) for zipped_element in my_zipped_list]
[{'class': 'class1', 'img': '1.jpg',  'sentence': 'Good for health.'},
 {'class': 'class5', 'img': '12.jpg', 'sentence': 'Good luck.'}]