Basic list/dictionary question

Daniel Jowett daniel.jowett at gmail.com
Wed Nov 11 07:16:22 EST 2009


Greetings,

I'm trying to categorize items in a list, by copying them into a
dictionary...
A simple example with strings doesn't seem to work how I'd expect:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> d = {}
>>> d = d.fromkeys(basket, [])
>>> d
{'orange': [], 'pear': [], 'apple': [], 'banana': []}
>>> for fruit in basket:
...     d[fruit].append(fruit)
...

No if I print d I'd EXPECT....
>>> d
{'orange': ['orange', 'orange'], 'pear': ['pear'], 'apple': ['apple',
'apple'], 'banana': ['banana']}

But what I GET is....
>>> d
{'orange': ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'pear':
['apple', 'orange', 'apple', 'pear', 'orange', 'banana'], 'apple': ['apple',
'orange', 'apple', 'pear', 'orange', 'banana'], 'banana': ['apple',
'orange', 'apple', 'pear', 'orange', 'banana']}
>>>

>From what I can work out, there is only ONE list that is referenced from the
dictionary 4 times. Which would be because the *same empty list* is assigned
to every key in the dictionary by the "fromkeys" line. But that seems
*seriously
*counter-intuitive to me...

Would anyone beg to differ and try to rewire my thinking? (I'm from a Java
background if that helps)

I've already solved the problem a different way, but I am concerned about
this counter-intuitiveness as I see it.

rgds,
Daniel Jowett
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091111/49169d84/attachment.html>


More information about the Python-list mailing list