I have the following list
a = ['Bananas', 'Ananas', 'Peach', 'Grapes', 'Oranges']
and want to have it as a list of dicts like
b = [{"fruit": "Bananas"},{"fruit": "Ananas"},{"fruit": "Peach"},{"fruit": "Grapes"},{"fruit": "Oranges"}]
How can that be done?
你可以这样做: b = [{'fruit':f} for f in a]
These are actually dictionaries not sets inside the list, you can give a try to list comprehension:
a = ['Bananas', 'Ananas', 'Peach', 'Grapes', 'Oranges']
b = [{"fruit": x} for x in a]
print(b)
如果你想有一个关键的fruit
,你应该使用列表理解:
b = [{ 'fruit': x } for x in a ]
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.