Help with list indexes

I am trying to make a bot while learning discord.py, and I was wondering why this did not work:

def create_embed(self, data):
        embed = discord.Embed(title=f"User List Page {self.current_page} / {int(len(self.data) / self.sep) + 1}")
        for item in data:
            embed.add_field(name=item['label'], value=item[''], inline=False)
        return embed

It creates this error:

Traceback (most recent call last):
  File "/home/runner/NotifBot/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 113, in paginate
    await pagination_view.send(ctx)
  File "main.py", line 12, in send
    await self.update_message(self.data[:self.sep])
  File "main.py", line 23, in update_message
    await self.message.edit(embed=self.create_embed(data), view=self)
  File "main.py", line 17, in create_embed
    embed.add_field(name=item['label'], value=item[''], inline=False)
TypeError: string indices must be integers

Thanks :smiley:

item is a list not a dictionary

2 Likes

You are trying to use a string as an index to access a value from a dictionary or a list.

Replace item[''] with item['value'] or whatever the key is for the value in the item dictionary.

For example, if the item dictionary contains a key-value pair like {‘label’: ‘Username’, ‘value’: ‘JohnDoe’}, you should replace item[‘’] with item[‘value’].

The fixed code should be something like:

def create_embed(self, data):
    embed = discord.Embed(title=f"User List Page {self.current_page} / {int(len(self.data) / self.sep) + 1}")
    for item in data:
        embed.add_field(name=item['label'], value=item['value'], inline=False)
    return embed

:grin:

um that’s not really going to help since item isn’t a dictionary (why does that answer seem so chatgpt tho?)

2 Likes

Wait so what should I change (sry for noob)

1 Like

I don’t know what data is so ¯\_(ツ)_/¯ but my best bet is that you just change item['label'] and item['value'] to item[index1] and item[index2]

2 Likes

Data is a list with a few indexes

1 Like

What is “item”. The error says it is a string, which means you can’t use it as a dict.

1 Like

My repl is https://repl.it/@MiloCat/NotifBot

It is not like I can run it XD

1 Like

Look at the code maybe, you’ll see data is just this:

data = [“1”,”2”,”3”,”4”,”5”,”6”,”7”,”8”,”9”,”10”
I was testing pagination

item['label']. So you’re asking for the “label” of string “1”. How does that make sense? XD

There is actually an extension made by discord.py’s creator just for this, might want to check it out.

1 Like

Ooh what’s it called?

1 Like

I fixed it, but i’ll mark you as a solution @bigminiboss (sorry dragonhunter1)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.