[Solved]Re: Help with TypeError: Can't convert 'list' object to str implicitly
davea at davea.name
Thu Feb 6 07:08:38 CET 2014
dave em <daveandem2000 at gmail.com> Wrote in message:
> Fixed the error and am now onto the next issue.
> Solution was to return a list (I think) and then break out the components of the list and put in the variable. Here is how we did it:
> secretWord = getRandomWord(words)
> print('The secretWord is ' + str(secretWord))
> print('The secretKey is ' + str(secretWord))
> #Change secretWord from a list to a str
> secretWord = secretWord
> def getRandomWord(wordDict):
> # This function returns a random string from the passed dictionary of lists of strings, and the key also.
> # First, randomly select a key from the dictionary:
> wordKey = random.choice(list(wordDict.keys()))
> print('The wordKey is ' + wordKey)
> # Second, randomly select a word from the key's list in the dictionary:
> wordIndex = random.randint(0, len(wordDict[wordKey]) - 1)
> print('The wordIndex is ' + str(wordIndex))
> print('The word is ' + wordDict[wordKey][wordIndex])
> return [wordDict[wordKey][wordIndex], wordKey]
Much better is to change the name of the function to match what
it's really doing. But I'll leave that to you.
Make the return logic look like:
word = [wordDict[wordKey][wordIndex]
return word, wordKey
Then the calling logic should be:
secretWord, key = getRandomSomethings (words)
print('The secretWord is ' + secretWord
print('The secretKey is ' + key
This way a name is not used for contradictory purposes.
More information about the Python-list