Einfacher Ansatz:
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']}
Mit 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']})
Mit groupby
von 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']}
Mit reduce
von 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']}
Danke für die Hilfe, die ich mit dem Standarddict Ansatz, der perfekt funktioniert hat und die anderen Ansätze sind auch sehr interessant. –