Is there a better way to do this snippet?

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Tue Apr 3 12:26:57 EDT 2012


nn <pruebauno 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.



More information about the Python-list mailing list