correcting unhashable type: 'dict_keys'

try to find the max value in a nested dictionary, but showed unhashable type: 'dict_keys'error

Suppose I have this dictionary:

d = {'A': {'a':2, 'b':2, 'c':0},
     'B': {'a':2, 'b':0, 'c':1}}

I want the code to return all the key(s) that contain maximum values within the dictionary (i.e. the maximum value in dictionary A is 2, and I want the code to return me the corresponding keys: 'a' and 'b')

['a','b']

here is the code I wrote:

max_value = max(d[Capital_Alph].values()))
return [key for key, value in d[Capital_Alph].items()
        if value == max_value]

So you have a dictionary with a str as value and a dict as key, You can do something like this:

d = {'A': {'a':2, 'b':2, 'c':0},
     'B': {'a':2, 'b':0, 'c':1}}
print(list(d['A'].keys()))

Returns:

['a', 'b', 'c']
[Finished in 0.8s]

Is this a viable solution to what you are trying to accomplish?

TypeError: unhashable type: 'list' Solution To fix this error, you can convert the 'list' into a hashable object like 'tuple' and then use it as a key for a dictionary as shown below

You can not use non-hashable datatypes as keys for sets or dict. You can accomplish your task by:

d = {'A': {'a':2, 'b':2, 'c':0},
     'B': {'a':2, 'b':0, 'c':1}}

max_v = {k:max(d[k].values()) for k in d }   # get the max value of the inner dict
print(max_v)

for inner in max_v:
    print("Max keys of dict {} are: {}".format(inner, 
          [k for k,v in d[inner].items() if v == max_v[inner]]))

Output:

{'A': 2, 'B': 2} # max values of inner dicts

Max keys of dict A are: ['a', 'b']
Max keys of dict B are: ['a']

The part [k for k,v in d[inner].items() if v == max_v[inner]])) is needed to get all inner keys (if multiple exists) that have the same maximum value.

Pandas TypeError: unhashable type: 'list'/'dict' Step #1: TypeError: unhashable type: 'list'/'dict'. TypeError: unhashable type: 'dict' when using apply/transform? Step #2: How to detect if column contains list or dict. The first step when the error appears is to identify the columns Step #3:

There are two errors in your code: there are too many ) characters in your calculation of max_value and you can't use return outside a function.

But if I fix those issues and do this:

>>> d = {'A': {'a':2, 'b':2, 'c':0},
         'B': {'a':2, 'b':0, 'c':1}}
>>> Capital_Alph = "A" 
>>> max_value = max(d[Capital_Alph].values())
>>> [key for key, value in d[Capital_Alph].items()
         if value == max_value]
['a', 'b']

it's clear that there isn't a lot else wrong here. To avoid complicating things I didn't put the obvious loop around this:

for Capital_Alph in d:

but you can manage that on your own. Your error message is because you tried to make Capital_Alph a dict_keys object, in other words d.keys(), and use that as a key. You can't do that. You have to step through the list of dictionary keys yourself.

This error shows that the my_dict key [1,2,3] is List and List is not a hashable type in Python. Dictionary keys must be immutable types and list is a mutable type. Fix: Cast list to a tuple You'll have to change your list into tuples if you want to put them as keys in your dictionary.

I have tried to write the properties in Dict as well as OrderdDict format, but still keep receiving Type error: unhashable type: 'Dict' or Type error: unhashable type: 'collections.OrderedDict'. I consulted several sources, including: Using Fiona to write a new shapefile from scratch; Fiona - Preffered method for defining a schema

TypeError: unhashable type: 'set' So, I either need to resolve why I am receiving this and fix it or try another approach, of course. Any advice would be greatly appreciated.

In simple word Mutable objects are not hashable. Example : List ,Carray , sets ,Dictionary ,Collections.deque etc. In any language it is considered wise to call mutable object not hashable because it's hash can be changed by it's mutability.

Comments
  • return only makes sense in functions. You code does not. Please fix your code so it is a complete minimal reproducible example.
  • values of your dictionary are dictionaries. it makes no sense to compare them
  • max(d[Capital_Alph].values())) has two opening parentheses, but three closing ones -> heed Patrick Artners's prompt, if not good general advice.
  • Thank you for your response, but actually I want the code to return all the keys that contains maximum value (i.e. I want the code to return 'a' and 'b' for dictionary A since 2 is the maximum value in A)