当前位置: 动力学知识库 > 问答 > 编程问答 >

List into json format using Python

问题描述:

I have a list like below...

lst = ['dosa','idly','sambar']

i need to convert the above data to below format by using Python.

[{'menuitem': 'idly'},

{'menuitem': 'dosa'},

{'menuitem': 'sambar'},

]

Thanks.

网友答案:

Using list comprehension, make a list of dictionaries:

>>> lst = ['dosa','idly','sambar']
>>> [{'menuitem': x} for x in lst]
[{'menuitem': 'dosa'}, {'menuitem': 'idly'}, {'menuitem': 'sambar'}]

Then, convert it to json using json.dumps:

>>> import json
>>> json.dumps([{'menuitem': x} for x in lst])
'[{"menuitem": "dosa"}, {"menuitem": "idly"}, {"menuitem": "sambar"}]'
网友答案:
lst = ['dosa','idly','sambar']
x="menuitem"
print map(lambda i:{x:i},lst)

Output: [{'menuitem': 'dosa'}, {'menuitem': 'idly'}, {'menuitem': 'sambar'}]

分享给朋友:
您可能感兴趣的文章:
随机阅读: