Why no list as dict key?
Chris Angelico
rosuav at gmail.com
Wed Apr 20 14:28:41 EDT 2022
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
More information about the Python-list
mailing list