这应该是一个简单的问题,但因为我不太熟悉Python,所以我还没有完全弄清楚它的工作原理。 我有以下csv文件
name ; type
apple ; fruit
pear ; fruit
cucumber ; vegetable
cherry ; fruit
green beans ; vegetable
我想要实现的是列出所有不同类型及其对应的名称,例如:
fruit: apple, pear, cherry
vegetable: cucumber, green beans
使用csv.DictReader读取csv文件后,我可以生成一个字典列表,保存在变量alldata中。
alldata =
[
{'name':'apple', 'type':'fruit'},
{'name':'pear', 'type':'fruit'},
...
]
现在我需要从alldata中获取所有不同类型值的列表。
types = ??? #it should contain [fruit, vegetable]
这样我就可以迭代列表并提取与这些类型相对应的名称:
foreach type in types
list_of_names = ??? #extract all values of alldata["type"]==type and put them in a new list
print type + ': ' + list_of_names
有人知道如何实现这个吗?
set(row["type"] for row in alldata)
- michaelmeyer