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

mad*_*hon 3 python arrays grouping dictionary

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

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

result = {'animal': ['cat', 'dog'], 'bird': 'crow'}
Run Code Online (Sandbox Code Playgroud)

我怎么能这么做呢?

Dan*_*sky 5

简单的方法:

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']}
Run Code Online (Sandbox Code Playgroud)

使用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']})
Run Code Online (Sandbox Code Playgroud)

使用groupby来自itertools

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']}
Run Code Online (Sandbox Code Playgroud)

使用reduce来自functools

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']}
Run Code Online (Sandbox Code Playgroud)