Why no list as dict key?

Abdur-Rahmaan Janhangeer arj.python at gmail.com
Wed Apr 20 22:22:53 EDT 2022


Thanks everybody,

In the the event spam is appended a value, then looking for [1,2] does not
return
anything but looking for [1,2,3] yes. But i gather the way dictionaries are
implemented
makes it difficult to do so ...

Maybe hashes should point to an object rather than being the hash of an
object themselves.
Maybe the speed drop is not worth it.

Kind Regards,

Abdur-Rahmaan Janhangeer
about <https://compileralchemy.github.io/> | blog
<https://www.pythonkitchen.com>
github <https://github.com/Abdur-RahmaanJ>
Mauritius


On Wed, Apr 20, 2022 at 10:35 PM Chris Angelico <rosuav at gmail.com> wrote:

> On Thu, 21 Apr 2022 at 04:23, Abdur-Rahmaan Janhangeer
> <arj.python at gmail.com> wrote:
> >
> > Greetings list,
>
> Greetings tuple,
>
> > Using Python3.9, i cannot assign a list [1, 2] as key
> > to a dictionary. Why is that so? Thanks in advanced!
> >
>
> Because a list can be changed, which would change what it's equal to:
>
> >>> spam = [1, 2]
> >>> ham = [1, 2, 3]
> >>> spam == ham
> False
> >>> spam.append(3)
> >>> spam == ham
> True
>
> If you use spam as a dict key, then mutate it in any way, it would
> break dict invariants of all kinds (eg you could also have used ham as
> a key, and then you'd have duplicate keys).
>
> Instead, use a tuple, which can't be mutated, is always equal to the
> same things, and is hashable, which means it can be used as a key:
>
> >>> spam = (1, 2)
> >>> ham = (1, 2, 3)
> >>> {spam: "spam", ham: "ham"}
> {(1, 2): 'spam', (1, 2, 3): 'ham'}
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>


More information about the Python-list mailing list