m654 m654 - 5 months ago 24
Python Question

Python chatbot - TypeError: list indices must be integers, not str

I've created a simple chatbot using Python, but when I try to use it, it gives me an error:

TypeError: list indices must be integers, not str

I'll get into the error later, but first I'll explain what the bot should do. The bot has a database, represented by a dictionary, in which all of the user's and bot's responses are stored.

  1. First of all, it outputs "Hi!"

  2. The user is asked for input.

  3. Every output has some responses associated with it. The output is stored in keys in the dictionary, and responses are in a list, which is the key's value.

  4. The bot's output is chosen randomly from the list of responses associated with the user's input.

  5. If the input isn't in the dictionary, then it will be added. Also, the input will be echoed by the bot.

  6. Repeat this forever.

(Sorry if the explanation was bad, but maybe if you keep reading you might understand.)

So, here is an example of what the bot should do.

BOT> Hi!
YOU> Hello!
BOT> Hello!
YOU> How do you do?
BOT> How do you do?
YOU> I'm fine, thanks.
BOT> I'm fine, thanks.
YOU> Hello!
BOT> How do you do?
YOU> I'm fine thanks.
BOT> Hello!

Here's the code I'm using (I excluded the parts that aren't needed)

import pickle
import random

class Bot:
def __init__(self, current, database, saveFile):
self.current = "Hi!"
self.database = []

def say(self, text):
print("BOT> " + text)
self.current = text

def evaluate(self, text):
if text in self.database:

self.database[text] = []

bot = Bot("", {})

while 1:
bot.evaluate(input("YOU> "))

And now, onto the problem I'm having.

When I try to talk to the bot, I get the error
TypeError: list indices must be integers, not str
. It was pointing to the line of code
self.database[text] = []
Here's an example:

BOT> Hi!
YOU> Hello!

I don't know what's going on, so I don't know what I should do to try and fix it. I thought the code would work right, but it doesn't... Could anybody give me a little help?


self.database is a list. List items are accessed by specifying their position within the list, for example self.database[0] for the first item and self.database[4] for the fifth item.

You're trying to use text as a list position, which makes no sense.

If you want to store items based on a text key instead of an integer position, use a dictionary instead of a list.