Search code examples
python-3.xdefaultdict

how to put variable in python defaultdict call


In a python defaultdict object (like obj1), I can call obj1['hello','there'] and get item. but when the input list is variable (for example: input_list), how I can call obj1[input_list]? when I call obj1[input_list], python raise this error:

TypeError: unhashable type: 'list'

when use obj1[*input_list], python returns:

SyntaxError: invalid syntax

So what is the correct way to put list as variable in defaultdict?


Solution

  • The error TypeError: unhashable type: 'list' states that list is not hashable, but a dict always needs a hashable key!
    If you test my_normal_dict[2,3] you can see that it actually treats these two numbers as the tuple (2,3) because the error is KeyError: (2, 3), so you need to input a hashable iterable like a tuple.

    For example, my_dict[tuple(my_list)] should work, as long as all the elements of the tuple itself are hashable!
    Note though: If your list is large, it may be relevant that this needs to copy all elements into a tuple.