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

Steven D'Aprano steve at pearwood.info
Fri Jun 29 15:10:30 CEST 2012


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



More information about the Tutor mailing list