问题描述:

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

相关阅读:
Top