On Apr 3, 12:26 pm, Alain Ketterlin <al...@dpt-info.u-strasbg.fr> wrote: > nn <prueba...@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.) -- http://mail.python.org/mailman/listinfo/python-list