Sets in Python

prikar20 at gmail.com prikar20 at gmail.com
Thu Sep 20 05:46:08 CEST 2007


On Sep 19, 5:25 pm, Mark Dickinson <dicki... at gmail.com> wrote:
> On Sep 19, 7:26 pm, Karthik Gurusamy <kar1... at gmail.com> wrote:
>
> > If I did, a = [10, 20] and I did d[a]= 'foo', then a.append(30).
> > If dict complains key error on d[a] now, I won't be surprised. If I do
> > d[[10, 20, 30]], I will be surprised if it doesn't find the item. Of
> > course, in today's behavior the above is syntax error.
>
> It sounds as though you're proposing something like the following:
>
> >>> k = mylist([1, 2])
> >>> d = {k : 'test'}
> >>> d[k]
> 'test'
> >>> k.append(3)
> >>> d[k]
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> KeyError: [1, 2, 3]
>
> So far, so good.  But how do you explain the following to a confused
> newcomer?
>
> >>> d.keys()
> [[1, 2, 3]]
> >>> k in d.keys()
> True
> >>> k in d
> False
> >>> d[k]
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> KeyError: [1, 2, 3]
>
> In other words, to repeat Sion Arrowsmith's question, what would you
> expect d.keys() to return after a key of d has been modified?

In the new model, it should be the value at the time of addition.
That is [1,2] (not [1,2,3]). This does mean a copy of key in
maintained internally in the dict. I think today that's not needed
(just a reference to the key's object is sufficient).

Again, this may not be the most elegant solution; neither seems to be
the current requirement that keys must be immutable. Fundamentally
dict is a mapping; underneath it could even use other elaborate
algorithms (say for integer keys, an avl tree) -- there is no reason
to expose the the quirks of hashing to the programmer.

Karthik
>
> Mark





More information about the Python-list mailing list