0
# this doesn't work
invalid_dict = {[1, 5]: 'a', 5: 23}

# but this does
valid_dict = {(1, 5): 'a', 5: [23, 6]}
print(valid_dict)

I want to know what's the issue with invalid_dict that it doesn't work. I understand that a hash value is computed for each item in a dictionary for storing the key-value pair at that location in the memory. But it seems strange to me that hash value for the the tuple (1,5) can be computed but not for the list [1,5].

  • Because you're not allowed to use a list as a key in a dictionary. – khelwood Oct 23 '20 at 08:03
  • "*dictionaries are indexed by keys, which can be any **immutable** type*" from the [docs](https://docs.python.org/3/tutorial/datastructures.html#dictionaries). – Sash Sinha Oct 23 '20 at 08:04

1 Answers1

0

Because tuple (1, 5) is passed by value and list [1,5] by reference.

There is no technical reasons for Python no to index by list but such strict behavior prevents lots of different confusions and post probably is faster.

Imagine this code:

k = [1,5]
d = {k: 7}
print d[k] # returns 7
k.append(6)
print d[k] # what should be returned here? 7 because we put by k or nothing because we put by [1,5] and now it’s [1,5,6]?

Developers should not be confused by such cases.

It’s not the case with tuple because it’s passed as a copy and you have no access to modify copy that was passed to func or indexer statement.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Alexander Trakhimenok
  • 6,019
  • 2
  • 27
  • 52