[Python] shortcut?

larry price laprice at gmail.com
Sun May 21 23:33:23 PDT 2006


On 5/21/06, Rob Hudson <rob at euglug.net> wrote:
> Is there a Python shortcut for the following?
>
> if d.has_key(k):
>         d[k].append(v)
> else:
>         d[k] = [v]
>
> I'm keeping a dictionary of key:list pairs and I'm writing the above
> often.  I think I remember seeing a shortcut to something like this but
> I can't recall what it was.

possibly

 |  setdefault(...)
 |      D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

but that looks like something that could be awfully dependent on what
you've got in the dictionary and what the values are or could be. but
if you know that all entries are either absent or lists you could do

d.setdefault(k,[])
d[k].append(v)


More information about the Python mailing list