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

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


Hello,
 
I was wondering why, in the code below, dictionary 'a' can be populated while dictionary 'b' can't.
b.get(k, []) will not return the default value [], but 'None' if k is not present in 'b'. Why?
Of course, one could use try-except to do this, but I'd just like to understand why the .get() version does not work.
 
Thanks!
 
import random
 
a = {}
for i in range(100):
  k = random.randint(1, 10)
  a[k] = a.get(k, 0) + 1
print a
 
b = {}
process = lambda k: k**2
for i in range(100):
  k = random.randint(1, 10)
  v = process(k)
  b[k] = b.get(k, []).append(v) # <--- error!
print b



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?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120629/a914580b/attachment.html>


More information about the Tutor mailing list