How to overcome TypeError: unhashable type: 'list'
As indicated by the other answers, the error is to due to k = list[0:j]
, where your key is converted to a list. One thing you could try is reworking your code to take advantage of the split
function:
# Using with ensures that the file is properly closed when you're done
with open('filename.txt', 'rb') as f:
d = {}
# Here we use readlines() to split the file into a list where each element is a line
for line in f.readlines():
# Now we split the file on `x`, since the part before the x will be
# the key and the part after the value
line = line.split('x')
# Take the line parts and strip out the spaces, assigning them to the variables
# Once you get a bit more comfortable, this works as well:
# key, value = [x.strip() for x in line]
key = line[0].strip()
value = line[1].strip()
# Now we check if the dictionary contains the key; if so, append the new value,
# and if not, make a new list that contains the current value
# (For future reference, this is a great place for a defaultdict :)
if key in d:
d[key].append(value)
else:
d[key] = [value]
print d
# {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}
Note that if you are using Python 3.x, you'll have to make a minor adjustment to get it work properly. If you open the file with rb
, you'll need to use line = line.split(b'x')
(which makes sure you are splitting the byte with the proper type of string). You can also open the file using with open('filename.txt', 'rU') as f:
(or even with open('filename.txt', 'r') as f:
) and it should work fine.
Python, TypeError: unhashable type: 'list'
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
TypeError: unhashable type: 'list' when creating a new column
The problem is that when you pass df['B']
into top_frequent()
, df['B']
is a column of list, you can view is as a list of list.
So in your for j in a:
, you are getting item from outer list. For list of list, what you get is a list.
Then in k[j]
, you are using a list as key which is not supported by Python list. So it gives you the error TypeError: unhashable type: 'list'
.
You can try
df['C'] = df['B'].apply(top_frequent)
# or
df['C'] = df.apply(lambda row: top_frequent(row['B']), axis=1)
Besides you can use a more pandas way to do this
df['C'] = df['B'].apply(lambda x: (lambda y: (y[y==y.max()].index.tolist()))(pd.Series(x).value_counts()))
TypeError unhashable type 'list'
Your code, somewhere, is doing from re import search
(or, shudders, from re import *
) at global scope. You then fail to properly invoke search
on self
, so it finds the re
module function and calls that instead. As a bonus error, you're not returning the values from your recursive calls, so any time you recurse you end up returning None
. The fixes are pretty simple at least, just change:
search(nums, target)
to:
return self.search(nums, target)
invoking the correct search
method on self
, and returning what it returns. The fix must be made in both places you're making the recursive call.
set.difference() raising TypeError: unhashable type 'list'
Do you store a list in one of your set-lists?
something like:
#ok
set([1,2,3])
{1, 2, 3}
# Error [3] is not hashable
set([1,2,[3]])
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'list'
In python, why do I get an error message of unhashable type:'list' when doing list(set(listB)-set(listA))?
sets require to hash the objects, and lists are not hashable (as they are mutable).
Thus you need to convert to tuple and back to list:
listA=[[0,1,2]]
listB=[[0,1,2],[0,1,3],[0,2,3]]
listC=list(map(list,set(map(tuple,listB))-set(map(tuple,listA))))
listC
output: [[0, 1, 3], [0, 2, 3]]
Related Topics
How to Dereference Variable Id'S
Pandas Add Column to Groupby Dataframe
How to Make Ball Bounce Off Wall with Pygame
How to Pass a List as a Command-Line Argument with Argparse
How to Do Parallel Programming in Python
How to Make an Immutable Object in Python
How to "Test" Nonetype in Python
Error: Command 'Gcc' Failed with Exit Status 1 While Installing Eventlet
Combine Several Images Horizontally with Python
Python Date String to Date Object
Why am I Getting "Indentationerror: Expected an Indented Block"
Unboundlocalerror with Nested Function Scopes
How to Validate Ip Address in Python
How to Validate a Url with a Regular Expression in Python
Some Unix Commands Fail with "<Command> Not Found", When Executed Using Python Paramiko Exec_Command