Reputation: 139
In C++, I will wirte map<vector<int>,int> mv;
But in Python,I get a error of "TypeError: unhashable type: 'list'"
I guess maybe in C++,map is a red-black tree ,but in Python,the dict is a hash table.
But how can I do the same thing like above in Python ?
Upvotes: 1
Views: 112
Reputation: 160073
As long as you don't need to resize the key, a tuple
would probably be the most efficient way to go about it:
mv = {}
mv[(1, 2, 3)] = 456
Upvotes: 1
Reputation: 369444
You cannot use list as dictionary key because it is not hashable.
>>> mv = {}
>>> mv[[1,2,3]] = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Use tuple instead.
>>> mv[(1,2,3)] = 2
>>> mv
{(1, 2, 3): 2}
Upvotes: 3