Is there a better way to do this snippet?
nn
pruebauno at latinmail.com
Tue Apr 3 11:37:28 EDT 2012
On Apr 3, 11:02 am, Alain Ketterlin <al... at dpt-info.u-strasbg.fr>
wrote:
> python <w.g.sned... at gmail.com> writes:
> > tag23gr is a list of lists each with two items.
> > g23tag is an empty dictionary when I run the for loop below.
> > When is is complete each key is a graphic name who's values are a list
> > of tags.
>
> > for item in tag23gr:
> > ... value, key = tuple(item)
> > ... if(g23tag.get(key)):
> > ... g23tag[key].append(value)
> > ... else:
> > ... g23tag[key] = [value]
>
> for item in tag23gr:
> g23tag.setdefault(item[0],[]).append(item[1])
>
> -- Alain.
Or alternatively:
from collections import defaultdict
g23tag = defaultdict(list)
for item in tag23gr:
....g23tag[item[0]].append(item[1])
More information about the Python-list
mailing list