Why cant I use a list as a dict key in python?

Why cant I use a list as a dict key in python?

Theres a good article on the topic in the Python wiki: Why Lists Cant Be Dictionary Keys. As explained there:

What would go wrong if you tried to use lists as keys, with the hash as, say, their memory location?

It can be done without really breaking any of the requirements, but it leads to unexpected behavior. Lists are generally treated as if their value was derived from their contents values, for instance when checking (in-)equality. Many would – understandably – expect that you can use any list [1, 2] to get the same key, where youd have to keep around exactly the same list object. But lookup by value breaks as soon as a list used as key is modified, and for lookup by identity requires you to keep around exactly the same list – which isnt requires for any other common list operation (at least none I can think of).

Other objects such as modules and object make a much bigger deal out of their object identity anyway (when was the last time you had two distinct module objects called sys?), and are compared by that anyway. Therefore, its less surprising – or even expected – that they, when used as dict keys, compare by identity in that case as well.

Why cant I use a list as a dict key in python?

>>> d = {repr([1,2,3]): value}
{[1, 2, 3]: value}

(for anybody who stumbles on this question looking for a way around it)

as explained by others here, indeed you cannot. You can however use its string representation instead if you really want to use your list.

Why cant I use a list as a dict key in python?

Just found you can change List into tuple, then use it as keys.

d = {tuple([1,2,3]): value}

Leave a Reply

Your email address will not be published.