python - Dictionary comprehension from a list of tuples with lists in them -
suppose have variable structured so:
results = [([123], 456), ([1, 2, 3], 456), ([2], 456)] i want dictionary using dictionary comprehension achieve doing so:
{item[1]:set(i item in results in item[0]) item in results} {456: {1, 2, 3, 123}} however suppose variable results becomes this:
[([123], 456), ([1, 2, 3], 456), ([2], 456), ([789], 'fizz')] i have unsuccessfully attempted change comprehension work on case. how achieve result through use of dictionary comprehension? know how using loops wish learn how achieved using comprehension. thanks!
edit:
output so:
{456: {1, 2, 3, 123}, 'fizz': {789}}
you can without comprehension, if insist on comprehension, here's solution uses itertools.groupby:
from itertools import groupby import operator f = operator.itemgetter(1) r = {k: set(i x in g in x[0]) k, g in groupby(results, f)} print(r) # {456: set([3, 1, 2, 123]), 'fizz': set([789])} caveat: note no presorting done, since items arranged according group key.
the solution more readable (say more pythonic) simple loop uses defaultdict:
from collections import defaultdict r = defaultdict(set) v, k in results: r[k].update(v) print(r) # defaultdict(<type 'set'>, {456: set([3, 1, 2, 123]), 'fizz': set([789])})
Comments
Post a Comment