Is there a better way to do this snippet?

nn pruebauno at latinmail.com
Tue Apr 3 14:03:44 EDT 2012


On Apr 3, 12:26 pm, Alain Ketterlin <al... at dpt-info.u-strasbg.fr>
wrote:
> nn <prueba... at latinmail.com> writes:
> >> > 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])
> > Or alternatively:
>
> > from collections import defaultdict
> > g23tag = defaultdict(list)
> > for item in tag23gr:
> > ....g23tag[item[0]].append(item[1])
>
> Very handy in that case, but in general I dislike the idea of silently
> inserting a default value when the access is a read, e.g., in
> x=g23tag[wrung]. Explicit is better than implicit, as they say. YMMV.
>
> -- Alain.

Valid point. Preferred choice depends on the access patterns to the
dict (e.g. one write and multiple reads, multiple writes and one loop
over items, etc.)



More information about the Python-list mailing list