Python return int - TypeError: unhashable type: 'dict'

3870 views python
5

def longest_word_in_string():

    word_len = []
    for word in string:
        word_len.append(len(word))

    lon_word = 0
    for i in word_len:
        if i > lon_word:
            lon_word = i

    return {

        total: int
    }

The code reads a string and then calculates the length of each word, returning the length of the longest word to the main function. The main function then returns the error:

line 97, in longest_word_in_string
lon_word: int
TypeError: unhashable type: 'dict'

Please advise me on why this code won't work.

answered question

You're returning a dictionary; in Python, the key, i.e. total in your question, is a string and should be wrapped in speech marks.

Also, int is not a variable in your function.

your code returns a dictionary which uses the total as key. It cannot be told from your code what it is but it seems to be a dictionary. Dictionaries cannot be used as keys since they are not hashable.

Minimal reproducible example please, i.e. include the function call, define string, and give the obtained and desired outputs

The error message doesn't match the code. Please post a MCVE (stackoverflow.com/help/mcve)

3 Answers

13

Neither total or int are defined and you're trying to return a dictionary with total as the key and int as the value.

Try

return lon_word

posted this
6

The compiler problem is at your return statement. {foo:bar} is creating a dictionary with one element total: int.
This will not work since nor total nor int is defined.

You should return string[lon_word].

Please use better names for naming your variables.

posted this
8

This is probably what you want, but you should also read the other answers for why your previous code did not work.

def longest_word_in_string(string):

    words = string.split(' ')

    longest = {'word': ''; 'length': 0}
    for word in words:
        if len(word) > longest['length']:
            longest['word'] = word
            longest['length'] = len(word)

    return longest

posted this

Have an answer?

JD

Please login first before posting an answer.