[Tutor] List methods inside a dictionary of list

Brett Ritter swiftone at swiftone.org
Mon Jul 11 16:33:24 CEST 2011


On Mon, Jul 11, 2011 at 9:26 AM, Rafael Turner
<steven.rafael.turner at gmail.com> wrote:
> I am playing lists and dictionaries and I came across this
> counter-intuitive result.
>
>>>> d = dict(zip(['a', 'q', 'c', 'b', 'e', 'd', 'g', 'j'],8*[[0]]))
...
>>>> d['a'].__setitem__(0,4)
...
>
> I was not expecting all the keys to be updated. Is there any
> documentation I could read on how different datatypes' methods and
> operators interact differently when inside a dictionary?  I would also
> like to find a way of being able to use list methods in side a
> dictionary so that

As has been mentioned, this isn't the dictionary doing anything weird,
this is that "8*[[0]]" gives you a list of 8 references to the same
list.  You can play with just that part and see that that's the source
of your issue.

To achieve what you are trying, try this instead:

d = dict([(x,[0]) for x in ['a', 'q', 'c', 'b', 'e', 'd', 'g', 'j']])

Can you understand how this behaves differently than 8*[[0]] ?  Check
the Python docs for array multiplication if you're confused, but the
basic idea is that "[0]" isn't getting evaluated freshly for every
piece in the array for 8*[[0]], but in a list comprehension it is.
-- 
Brett Ritter / SwiftOne
swiftone at swiftone.org


More information about the Tutor mailing list