我有一堆列表,其中包含彼此相关的元素,我想将它们转换为一个以列表作为值的字典:
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/