[英]Convert from list to list of dicts
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 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.