创建一个包含字典列表的单键列表
这应该是个简单的问题,但因为我对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读取这个文件,我可以生成一个字典列表,保存在变量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
有没有人知道怎么做到这一点?
3 个回答
1
使用 set
这种数据结构:
types = set((d['type'] for d in alldata))
5
你可以用列表推导式来解决这个问题:
types = set([data['type'] for data in alldata])
list_of_name = [data['name'] for data in alldata if data['type']==type]
2
更通用的方法是使用 itertools.groupby:
from itertools import groupby
food = [
{'name': 'apple', 'type': 'fruit'},
{'name': 'pear', 'type': 'fruit'},
{'name': 'parrot', 'type': 'vegetable'}]
for group, items in groupby(sorted(food, key=lambda x: x['type']), lambda x: x['type']):
print group, list(items) # here is group and items' objects in the group
结果是:
fruit [{'type': 'fruit', 'name': 'apple'}, {'type': 'fruit', 'name': 'pear'}]
vegetable [{'type': 'vegetable', 'name': 'parrot'}]
更新:在使用 groupby 之前先对字典进行排序。感谢 @mgilson 的提醒!
这个函数会创建一个迭代器,它会返回可迭代对象中连续的键和分组。这里的“键”是一个函数,用来计算每个元素的键值。如果没有指定或者是 None,默认的键函数就是返回元素本身。通常情况下,可迭代对象需要先按照相同的键函数进行排序。
https://docs.python.org/2/library/itertools.html#itertools.groupby