0

I'm trying to create a dictionary containing operands [a, b] as the key, and product (a*b) as the value. For example, it would look something like this.

Key (list): [2, 3]

Val (int): 6

My code grabs the operands (paired) and appends them to a list, which resets for every iteration. Then computes the product and stores that into a variable. Then, at the end of each iteration after forming the operand pairs (a, b) and computing the product (a * b), I try to store that into the dictionary h.

key = []  # Resets for each iteration
key.append(a)
key.append(b)
value = a * b
h[key] = value

When attempting to create a dictionary entry, I get the following error.

TypeError: unhashable type: 'list'

Is there any way to create such a dictionary? If so, how would I do it? Or would a tuple be better suited for this problem?

RCube123
  • 81
  • 6
  • 1
    A tuple as key is hashable (because one can't add, remove or exchange items in it) and would work. – Michael Butscher Mar 19 '20 at 03:05
  • Generally speaking, dictionary keys need to be **immutable** objects, which can’t change. Lists are mutable. Tuples are very similar to lists, but immutable. If you do `key = tuple(key)`, that will work. – Tom Zych Mar 19 '20 at 03:09
  • @TomZych the actual requirement is that they're hashable. It's intended that hashable things are immutable (because it's trivial to corrupt data otherwise), but you can define a hash operation for user-defined classes, and you can't really force immutability on them (you can only respect the documented interface). – Karl Knechtel Mar 19 '20 at 03:31

0 Answers0