Reputation: 294
Mainly I have this dictionary rhs
rhs
{{('1', '3'): [0.06081006262521797, 0.4965853037914095], ('1', '4'): [0.0018363047770289071], ('3', '2'): [0.4965853037914095]}
type(rhs1)
<class 'dict'>
I tried to normalize only the values in rhs and store them again in another dictionary rhs_normalized
so the sum of values for each key must equals 1 but I couldn't! I need to store them in this way to be able later to call each array of values belongs to a certain key like:
rhs_normalized
{('1', '3'): [0.10909682119561295, 0.8909031788043871], ('1', '4'): [1.0], ('3', '2'): [1.0]}
so I wrote
rhs
{{('1', '3'): [0.06081006262521797, 0.4965853037914095], ('1', '4'): [0.0018363047770289071], ('3', '2'): [0.4965853037914095]}
type(rhs1)
<class 'dict'>
rhs_normalized = {}
for each_array in list(rhs1.values()):
each_array_of_values_equal = []
for i in each_array :
each_array_of_values_equal.append(i/sum(each_array))
rhs_normalized[each_array] = each_array_of_values_equal
I got this error
...
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
TypeError: unhashable type: 'list'
I think the error because of rhs_normalized[each_array]
since, as I understood, I tried to use a list as a key for a dictionary and this key is not hashable!
It seems a common error for beginners so I tried many solutions available on the internet but without success. Thanks in advance for help.
Upvotes: 1
Views: 43
Reputation: 15120
You are using your lists as dict keys (which are unhashable and can't be used as keys). Per your example output, I think you mean to use the existing dict keys and transform the list values.
For example (simplified the process of building your second dict a bit):
data = {('1', '3'): [0.06081006262521797, 0.4965853037914095], ('1', '4'): [0.0018363047770289071], ('3', '2'): [0.4965853037914095]}
result = {k: [v / sum(vals) for v in vals] for k, vals in data.items()}
print(result)
# {('1', '3'): [0.10909682119561295, 0.8909031788043871], ('1', '4'): [1.0], ('3', '2'): [1.0]}
Upvotes: 1