2

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.

0

2 Answers 2

5

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"}]'
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for explanation. Although I expect pro don't just solve the questions
Its Working Good.Thanks.
2
lst = ['dosa','idly','sambar']
x="menuitem"
print map(lambda i:{x:i},lst)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.