python - 如何通过 Python 中单个字典的键对一堆列表进行分组

标签 python arrays dictionary grouping

我有一堆列表,其中包含彼此相关的元素,我想将它们转换为一个以列表作为值的字典:

list1 = ['cat', 'animal']
list2 = ['dog', 'animal']
list3 = ['crow', 'bird']

result = {'animal': ['cat', 'dog'], 'bird': 'crow'}

我该怎么做?

最佳答案

简单方法:

data = [['cat', 'animal'], ['dog', 'animal'], ['crow', 'bird']]

result = {}

for value, key in data:
    result[key] = result.get(key, []) + [value]

result #=> {'bird': ['crow'], 'animal': ['cat', 'dog']}

使用defaultdict:

from collections import defaultdict

data = [['cat', 'animal'], ['dog', 'animal'], ['crow', 'bird']]

result = defaultdict(list)

for value, key in data:
    result[key].append(value)

result #=> defaultdict(<class 'list'>, {'animal': ['cat', 'dog'], 'bird': ['crow']})

使用 itertools 中的 groupby:

from itertools import groupby

data = [['cat', 'animal'], ['dog', 'animal'], ['crow', 'bird']]

{k: [x[0] for x in g] for k, g in groupby(data, lambda x: x[1])}
#=> {'bird': ['crow'], 'animal': ['cat', 'dog']}

使用 functools 中的 reduce:

from functools import reduce

data = [['cat', 'animal'], ['dog', 'animal'], ['crow', 'bird']]

reduce(lambda a, e: dict(a, **{e[1]: a.get(e[1], []) + [e[0]]}), data, {})
#=> {'bird': ['crow'], 'animal': ['cat', 'dog']}

关于python - 如何通过 Python 中单个字典的键对一堆列表进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45908485/

相关文章:

python - django "in"子句是否要求列表有两个值?

python - 属性错误 : 'list' object has no attribute 'encode' when sending an email

python - 检索 ldap3 中所有属性的列表 (python3-ldap)

arrays - VBA:根据另一个数组对数组进行排序

c++ - 以随机顺序打印整数数组而不在C++中重复

python - 纯Python中dict的求和和计数列表

python - MySQL:pymysql 或 mysqldb 访问字典游标功能

java - 如何删除输出中的最后一个 “-”?

python - 从字典数据中删除 Unicode

c - 为什么这会在一个系统上给我带来段错误,而在另一个系统上却不会?