Preferred Python idiom for handling non-existing dictionary keys and why?

Peter Otten __peter__ at web.de
Fri Oct 10 16:25:34 EDT 2003


Terry Reedy wrote:

> Neither.  For me, both are superceded by
> 
> d={}
> for (k,v) in somedata():
>     d[k] = d.get(k, []).append(v)

This would have to look up the key twice, so it has no advantage over 

if k in d:
    d[k].append(v)
else:
    d[k] = [v]

Anyway, list.append() returns always None, so it does not work. 
I think you mean

d = {}
for (k, v) in somedata:
    d.setdefault(k, []).append(v)

There is a small overhead for throwing away a new list object if the key is
already in the dictionary, but I don't really care. 
(Or is the compiler smart enough to reuse the empty list?)

Peter




More information about the Python-list mailing list