我有一堆包含相互关联的元素的列表,我想将它们转换为以列表为值的单个字典:
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']})
使用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']}
使用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']}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句