python - 一键创建字典列表列表

标签 python list dictionary

这应该是一个简单的,但是因为我对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

有人知道如何实现吗?

最佳答案

你可以使用列表理解来解决这个问题:

types = set([data['type'] for data in  alldata])

list_of_name = [data['name'] for data in alldata if data['type']==type]

关于python - 一键创建字典列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25568964/

相关文章:

python - Python中的无限滚动背景

python - 如何在python中不使用[]将列表写入文件

python - 字典有 key 长度限制吗?

algorithm - 经典 Cracking the Coding 面试题的运行时间 a^3 + b^3 = c^3 + d^3?

python - 捕获所有 * 前面没有 < 的组

python - 从 Go 调用 Python 函数并获取函数返回值

python - 重复整数列表

python - 在 python 3 中使用链表进行三个(或更多)不同变量赋值的操作顺序

Python:这个 datetime.strptime 解析有什么问题?

C++ 如何访问和更改映射中对象的成员数据?