Preferred Python idiom for handling non-existing dictionary keys and why?
Dave Benjamin
ramen at lackingtalent.com
Fri Oct 10 16:03:12 EDT 2003
In article <jOWcnYmbcsYclhqiXTWJig at comcast.com>, Terry Reedy wrote:
>
> "Quentin Crain" <czrpb at yahoo.com> wrote in message
> news:mailman.1065807808.957.python-list at python.org...
>>
>> Which is perferred and why?
>
> Neither. For me, both are superceded by
>
> d={}
> for (k,v) in somedata():
> d[k] = d.get(k, []).append(v)
Not quite... append returns None, so you'll need to write that as two
separate statements, ie.:
d[k] = d.get(k, [])
d[k].append(v)
Or, just:
d.setdefault(k, []).append(v)
--
.:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
More information about the Python-list
mailing list