Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
do_work()
File "C:\pythonwork\readthefile080410.py", line 14, in do_work
populate_frequency5(e,data)
File "C:\pythonwork\readthefile080410.py", line 157, in populate_frequency5
data=medications_minimum3(data,[drug.upper()],1)
File "C:\pythonwork\readthefile080410.py", line 120, in medications_minimum3
counter[row[11]]+=1
TypeError: unhashable type: 'list'
I am getting the above error on this line:
data=medications_minimum3(data,[drug.upper()],1)
(I have also tried drug.upper() without brackets)
Here is a preview of this function:
def medications_minimum3(c,drug_input,sample_cutoff): #return sample cut off for # medications/physician
d=[]
counter=collections.defaultdict(int)
for row in c:
counter[row[11]]+=1
for row in c:
if counter[row[11]]>=sample_cutoff:
d.append(row)
write_file(d,'/pythonwork/medications_minimum3.csv')
return d
Does anyone know what I am doing wrong here?
I know that what must be wrong is the way I am calling this function, because I call this function from a different location and it works fine:
d=medications_minimum3(c,drug_input,50)
Thank you very much for your help!
The “TypeError: unhashable type: 'list'” error is raised when you try to assign a list as a key in a dictionary. To solve this error, ensure you only assign a hashable object, such as a string or a tuple, as a key for a dictionary.
The Python "TypeError: unhashable type: 'dict'" occurs when we use a dictionary as a key in another dictionary or as an element in a set . To solve the error, use a frozenset instead, or convert the dictionary into a JSON string before using it as a key.
Slice is not a hashable object, and therefore it cannot be used as a key to a dictionary. To solve this error, specify the appropriate key names for the values you want or use an iterable object like items() and iterate over the items in the dictionary.
We can solve this by adding each array element instead of the array object into the set. This should add all the elements of the array to the set.
counter[row[11]]+=1
You don't show what data
is, but apparently when you loop through its rows, row[11]
is turning out to be a list
. Lists are mutable objects which means they cannot be used as dictionary keys. Trying to use row[11]
as a key causes the defaultdict
to complain that it is a mutable, i.e. unhashable, object.
The easiest fix is to change row[11]
from a list
to a tuple
. Either by doing
counter[tuple(row[11])] += 1
or by fixing it in the caller before data
is passed to medications_minimum3
. A tuple simply an immutable list, so it behaves exactly like a list does except you cannot change it once it is created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With