[Tutor] .get dicionary question (mutability??)

Albert-Jan Roskam fomcl at yahoo.com
Fri Jun 29 15:45:14 CEST 2012


Hi Steven,
 
Thanks for helping me. It makes more sense now. Calling append() on the datatype list returns None but calling __add__ on the datatype int returns, well, the result. Somehow it makes more sense to me when writing + as __add__
a[k] = a.get(k, 0).__add__(1)
b[k] = b.get(k, []]).__add__([v])
>>> x = 1
>>> y = []
>>> z = y.append(x)
>>> z is None
True
 
 
Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 


>________________________________
>From: Steven D'Aprano <steve at pearwood.info>
>To: Python Mailing List <tutor at python.org> 
>Sent: Friday, June 29, 2012 3:10 PM
>Subject: Re: [Tutor] .get dicionary question (mutability??)
>
>Albert-Jan Roskam wrote:
>> b.get(k, []) will not return the default value [], but 'None' if k is not present in 'b'. Why?
>
>Incorrect. b.get(k, []) returns the default value [] as expected.
>
>You then call the append method on that list, which returns None, and then you assign that result (None) to the dict item.
>
>
>> b = {}
>> process = lambda k: k**2
>
>"process"? Surely "squared" would be a more descriptive and less misleading name.
>
>
>> for i in range(100):
>>  k = random.randint(1, 10)
>>  v = process(k)
>>  b[k] = b.get(k, []).append(v) # <--- error!
>
>If b.get(k, []) did not return a list, the call to append would fail with AttributeError.
>
>
>Here are two ways to solve this correctly:
>
>
>for i in range(100):
>    k = random.randint(1, 10)
>    v = process(k)
>    b.setdefault(k, []).append(v)
>
>
>for i in range(100):
>    k = random.randint(1, 10)
>    v = process(k)
>    b[k] = b.get(k, []) + [v]
>
>
>The first way is more efficient and will probably be faster as the lists get longer. For small lists it is unlikely to make much difference.
>
>
>
>-- Steven
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>To unsubscribe or change subscription options:
>http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120629/3e697960/attachment.html>


More information about the Tutor mailing list