Typeerror list indices must be integers or slices not str ошибка

Может кто подсказать как исправить?

Cursor.execute(_SQL, (pricelist[‘name’]))
TypeError: list indices must be integers or slices, not str

def BB_parse(base_url, headers):
    pricelist = []
    session = requests.Session()
    request = session.get(base_url, headers = headers)
    if request.status_code == 200:
        soup = bs(request.content, 'lxml')
        container_main = soup.find_all('div', {'class': 'content-wrapper'})
        for c1 in container_main:
            try:
                article = c1.find('div', {'class': 'article'}).text.strip().replace("Артикул: ", "")
                name = c1.select('h1')[0].text
                description = c1.find('div', {'class': 'description'}).text.strip()
                available = c1.find('div', {'class': 'avl'}).text.strip()
                price = c1.find('span', {'class': 'catalog-detail-item-price' }).text.replace("Цена:", "").replace("тг.", "").replace("за шт", "").strip()
                oldprice = c1.find('span', {'class': 'catalog-detail-item-price-old' }).text.replace("Цена:", "").replace("тг.", "").replace("за шт", "").replace(" ", "").strip()
                Category1 = c1.find_all('span', {'itemprop': 'title'})[1].text
                Category2 = c1.find_all('span', {'itemprop': 'title'})[2].text
                Category3 = c1.find_all('span', {'itemprop': 'title'})[3].text
                catalog_detail_pictures = c1.find_all('div', {'class': 'catalog-detail-pictures'})
                image1 = c1.find_all('a', {'rel': 'lightbox'})[0]['href']
                image2 = c1.find_all('a', {'rel': 'lightbox'})[1]['href']
                image3 = c1.find_all('a', {'rel': 'lightbox'})[2]['href']
            except:
                pass


            for count, tag in enumerate(soup.find_all(class_='name')):
                try:
                    if tag.text == 'ISBN':
                       code = soup.find_all(class_='val')[count].text
                    if tag.text == 'Издательство':
                       Publish = soup.find_all(class_='val')[count].text
                    if tag.text == 'Авторы':
                       Authors = soup.find_all(class_='val')[count].text
                    if tag.text == 'Серия':
                       Series = soup.find_all(class_='val')[count].text
                    if tag.text == 'Переплет':
                       Blinding = soup.find_all(class_='val')[count].text
                    if tag.text == 'Количество страниц':
                       Count_Page = soup.find_all(class_='val')[count].text
                    if tag.text == 'Ширина':
                       Width = soup.find_all(class_='val')[count].text
                    if tag.text == 'Высота':
                       Height = soup.find_all(class_='val')[count].text
                    if tag.text == 'Дата последнего тиража':
                       Date = soup.find_all(class_='val')[count].text


                except:
                  pass

            pricelist.append({
                     'name': name,
                     'article': article,
                     'price': price,
                     'oldprice': oldprice,
                     'available': available,
                     'code': code,
                     'Publish': Publish,
                     'Authors': Authors,
                     'Series': Series,
                     'Blinding': Blinding,
                     'Count_Page': Count_Page,
                     'Width': Width,
                     'Height': Height,
                     'Date': Date,
                     'Category1': Category1,
                     'Category2': Category2,
                     'Category3': Category3,
                     'image1': image1,
                     'image2': image2,
                     'image3': image3
                })

        write_sql(pricelist)
        print(len(pricelist))



    else:
        print('ERROR or Done. Status_code = ' + str(request.status_code))

    return pricelist

def write_sql(pricelist):
    DB = {'host': '',
         'user': '',
         'password': '',
         'database': ''}


    conn = mysql.connector.connect(**DB)
    Cursor = conn.cursor()

    _SQL = "INSERT INTO products (Наименование, Артикул, Цена, Старая_цена, Наличие, Код, Издательство, Авторы, Серия, Переплет, Количество_страниц, Ширина, Высота, Дата_тиража, Родительская_категория, Категория, Подкатегория, Картикнка_1 Картикнка_2, Картикнка_3) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    Cursor.execute(_SQL, (pricelist['name'],
        pricelist['article'],
        pricelist['price'],
        pricelist['oldprice'],
        pricelist['available'],
        pricelist['code'],
        pricelist['Publish'],
        pricelist['Authors'],
        pricelist['Series'],
        pricelist['Blinding'],
        pricelist['Count_Page'],
        pricelist['Width'],
        pricelist['Height'],
        pricelist['Date'],
        pricelist['Category1'],
        pricelist['Category2'],
        pricelist['Category3'],
        pricelist['image1'],
        pricelist['image2'],
        pricelist['image3'],
        ))
    DB.commit()
    Cursor.close()
    DB.close()


BB_parse(base_url, headers)

TypeError: list indices must be integers or slices, not str

This error occurs when using a string for list indexing instead of indices or slices. For a better understanding of list indexing, see the image below, which shows an example list labeled with the index values:

Using indices refers to the use of an integer to return a specific list value. For an example, see the following code, which returns the item in the list with an index of 4:

value = example_list[4] # returns 8

Using slices means defining a combination of integers that pinpoint the start-point, end-point and step size, returning a sub-list of the original list. See below for a quick demonstration of using slices for indexing. The first example uses a start-point and end-point, the second one introduces a step-size (note that if no step-size is defined, 1 is the default value):

value_list_1 = example_list[4:7]   # returns indexes 4, 5 and 6 [8, 1, 4]
value_list_2 = example_list[1:7:2] # returns indexes 1, 3 and 5 [7, 0, 1]

As a budding Pythoneer, one of the most valuable tools in your belt will be list indexing. Whether using indices to return a specific list value or using slices to return a range of values, you’ll find that having solid skills in this area will be a boon for any of your current or future projects.

Today we’ll be looking at some of the issues you may encounter when using list indexing. Specifically, we’ll focus on the error TypeError: list indices must be integers or slices, not str, with some practical examples of where this error could occur and how to solve it.

For a quick example of how this could occur, consider the situation you wanted to list your top three video games franchises. In this example, let’s go with Call of Duty, Final Fantasy and Mass Effect. We can then add an input to the script, allowing the user to pick a list index and then print the corresponding value. See the following code for an example of how we can do this:

favourite_three_franchises = ['Call of Duty', 'Final Fantasy', 'Mass Effect']

choice = input('Which list index would you like to pick (0, 1, or 2)? ')

print(favourite_three_franchises[choice])

Out:

Which list index would you like to pick (0, 1, or 2)?  0

Out:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-34186a0c8775> in <module>
      3 choice = input('Which list index would you like to pick (0, 1, or 2)? ')
      4 
----> 5 print(favourite_three_franchises[choice])

TypeError: list indices must be integers or slices, not str

We’re getting the TypeError in this case because Python is detecting a string type for the list index, with this being the default data type returned by the input() function. As the error states, list indices must be integers or slices, so we need to convert our choice variable to an integer type for our script to work. We can do this by using the int() function as shown below:

favourite_three_franchises = ['Call of Duty', 'Final Fantasy', 'Mass Effect']

choice = int(input('Which list index would you like to pick (0, 1, or 2)? '))

print(favourite_three_franchises[choice])

Out:

Which list index would you like to pick (0, 1, or 2)?  1

Our updated program is running successfully now that 1 is converted from a string to an integer before using the choice variable to index the list, giving the above output.

Building on the previous example, let’s create a list of JSON objects. In this list, each object will store one of the game franchises used previously, along with the total number of games the franchise has sold (in millions). We can then write a script to output a line displaying how many games the Call of Duty franchise has sold.

favourite_three_franchises = [
  {
    "Name" : "Call of Duty", 
    "Units Sold" : 400
  },
  {
    "Name" : "Final Fantasy",
    "Units Sold" : 150
  },
  {
    "Name" : "Mass Effect",
    "Units Sold" : 16
  }
]

if favourite_three_franchises["Name"] == 'Call of Duty':
    print(f'Units Sold: {favourite_three_franchises["Units Sold"]} million')

Out:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-f61f169290d0> in <module>
     14 ]
     15 
---> 16 if favourite_three_franchises["Name"] == 'Call of Duty':
     17     print(f'Units Sold: {favourite_three_franchises["Units Sold"]} million')
TypeError: list indices must be integers or slices, not str

This error occurs because we have accidentally tried to access the dictionary using the "Name" key, when the dictionary is inside of a list. To do this correctly, we need first to index the list using an integer or slice to return individual JSON objects. After doing this, we can use the "Name" key to get the name value from that specific dictionary. See below for the solution:

for i in range(len(favourite_three_franchises)):
    if favourite_three_franchises[i]["Name"] == 'Call of Duty':
        print(f'Units Sold: {favourite_three_franchises[i]["Units Sold"]} million')

Out:

Units Sold: 400 million

Our new script works because it uses the integer type i to index the list and return one of the franchise dictionaries stored in the list. Once we’ve got a dictionary type, we can then use the "Name" and "Units Sold" keys to get their values for that franchise.

A slightly different cause we can also take a look at is the scenario where we have a list of items we’d like to iterate through to see if a specific value is present. For this example, let’s say we have a list of fruit and we’d like to see if orange is in the list. We can easily make the mistake of indexing a list using the list values instead of integers or slices.

fruit_list = ['Apple', 'Grape', 'Orange', 'Peach']

for fruit in fruit_list:
    if fruit_list[fruit] == 'Orange':
        print('Orange is in the list!')

Out:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-0a8aff303bb3> in <module>
      2 
      3 for fruit in fruit_list:
----> 4     if fruit_list[fruit] == 'Orange':
      5         print('Orange is in the list!')
TypeError: list indices must be integers or slices, not str

In this case, we’re getting the error because we’ve used the string values inside the list to index the list. For this example, the solution is pretty simple as we already have the list values stored inside the fruit variable, so there’s no need to index the list.

fruit_list = ['Apple', 'Grape', 'Orange', 'Peach']

for fruit in fruit_list:
    if fruit == 'Orange':
        print('Orange is in the list!')

Out:

Orange is in the list!

As you can see, there was no need for us to index the list in this case; the list values are temporarily stored inside of the fruit variable as the for statement iterates through the list. Because we already have the fruit variable to hand, there’s no need to index the list to return it.

For future reference, an easier way of checking if a list contains an item is using an if in statement, like so:

fruit_list = ['Apple', 'Grape', 'Orange', 'Peach']

if 'Orange' in fruit_list:
    print('Orange is in the list!')

Out:

Orange is in the list!

Or if you want the index of an item in the list, use .index():

idx = fruit_list.index('Orange')
print(fruit_list[idx])

Bear in mind that using .index() will throw an error if the item doesn’t exist in the list.

Summary

This type error occurs when indexing a list with anything other than integers or slices, as the error mentions. Usually, the most straightforward method for solving this problem is to convert any relevant values to integer type using the int() function. Something else to watch out for is accidentally using list values to index a list, which also gives us the type error.

friends = ['Сергей', 'Соня', 'Дима', 'Алина', 'Егор']

# присвойте переменной index такое значение,
# чтобы из списка friends была выбрана Алина
index = friends[3]

print('Привет, ' + friends[index] + ', я Анфиса!')

На это питон выдает ошибку

Traceback (most recent call last):
File «main.py», line 7, in
print(‘Привет, ‘ + friends[index] + ‘, я Анфиса!’)
TypeError: list indices must be integers or slices, not str

If you are accessing the elements of a list in Python, you need to access it using its index position or slices. However, if you try to access a list value using a string instead of integer to access a specific index Python will raise TypeError: list indices must be integers or slices, not str exception.

We can resolve the error by converting the string to an integer or if it is dictionary we can access the value using the format list_name[index_of_dictionary]['key_within_dictionary']

In this tutorial, we will learn what “list indices must be integers or slices, not str” error means and how to resolve this TypeError in your program with examples.

Lists are always indexed using a valid index number, or we can use slicing to get the elements of the list. Below is an example of indexing a list.

# Example 1: of list indexing
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print(my_list[5])

# Example 2: of list slicing
fruits = ["Apple", "Orange", "Lemon", "Grapes"]
print("Last 2 fruits is", fruits[2:4])

Output

6
Last 2 fruits is ['Lemon', 'Grapes']

The first example is we use an integer as an index to get the specific element of a list.

In the second example, we use a Python slicing technique by defining a start point and end-point to retrieve the sublist from the main list.

Now that we know how to access the elements of the list, there are several scenarios where developers tend to make mistakes, and we get a TypeError. Let us take a look at each scenario with examples.

Scenario 1: Reading string input from a user

It’s the most common scenario where we do not convert the input data into a valid type in Menu-driven programs, leading to TypeError. Let us take an example to reproduce this issue.

Consider an ATM menu-driven example where the user wants to perform certain operations by providing the input to the program.

menu = ["Deposit Cash", "Withdraw Case", "Check Balance", "Exit"]
choice = input(
    'Choose what would you like to perform (Valid inputs 0, 1, 2, 3)')
print(menu[choice])

Output

Choose what would you like to perform (Valid inputs 0, 1, 2, 3)2
Traceback (most recent call last):
  File "C:PersonalIJSCodemain.py", line 13, in <module>
    print(menu[choice])
TypeError: list indices must be integers or slices, not str

When the user inputs any number from 0 to 3, we get TypeError: list indices must be integers or slices, not str, because we are not converting the input variable “choice” into an integer, and the list is indexed using a string.

We can resolve the TypeError by converting the user input to an integer, and we can do this by wrapping the int() method to the input, as shown below.

menu = ["Deposit Cash", "Withdraw Case", "Check Balance", "Exit"]
choice = int(input(
    'Choose what would you like to perform (Valid inputs 0, 1, 2, 3) - ' ))
print(menu[choice])

Output

Choose what would you like to perform (Valid inputs 0, 1, 2, 3) - 2
Check Balance

Scenario 2: Trying to access Dictionaries list elements using a string

Another reason we get TypeError while accessing the list elements is if we treat the lists as dictionaries. 

In the below example, we have a list of dictionaries, and each list contains the actor and name of a movie.

actors = [
    {
        'name': "Will Smith",
        'movie': "Pursuit of Happiness"
    },

    {
        'name': "Brad Pitt",
        'movie': "Ocean's 11"
    },
    {
        'name': "Tom Hanks",
        'movie': "Terminal"
    },
    {
        'name': "Leonardo DiCaprio",
        'movie': "Titanic"
    },
    {
        'name': "Robert Downey Jr",
        'movie': "Iron Man"
    },
]

actor_name = input('Enter the actor name to find a movie -   ')
for i in range(len(actors)):
    if actor_name.lower() in actors['name'].lower():
        print('Actor Name: ', actors['name'])
        print('Movie: ', actors['movie'])
        break
else:
    print('Please choose a valid actor')

Output

Enter the actor name to find a movie -   Brad Pitt
Traceback (most recent call last):
  File "C:PersonalIJSCodeprogram.py", line 27, in <module>
    if actor_name.lower() in actors['name'].lower():
TypeError: list indices must be integers or slices, not str

We need to display the movie name when the user inputs the actor name.

When we run the program, we get TypeError: list indices must be integers or slices, not str because we are directly accessing the dictionary items using the key, but the dictionary is present inside a list. 

If we have to access the particular value from the dictionary, it can be done using the following syntax.

list_name[index_of_dictionary]['key_within_dictionary']

We can resolve this issue by properly iterating the dictionaries inside the list using range() and len() methods and accessing the dictionary value using a proper index and key, as shown below.

actors = [
    {
        'name': "Will Smith",
        'movie': "Pursuit of Happiness"
    },

    {
        'name': "Brad Pitt",
        'movie': "Ocean's 11"
    },
    {
        'name': "Tom Hanks",
        'movie': "Terminal"
    },
    {
        'name': "Leonardo DiCaprio",
        'movie': "Titanic"
    },
    {
        'name': "Robert Downey Jr",
        'movie': "Iron Man"
    },
]

actor_name = input('Enter the actor name to find a movie -   ')
for i in range(len(actors)):
    if actor_name.lower() in actors[i]['name'].lower():
        print('Actor Name: ', actors[i]['name'])
        print('Movie: ', actors[i]['movie'])
        break
else:
    print('Please choose a valid actor')

Output

Enter the actor name to find a movie -   Brad Pitt
Actor Name:  Brad Pitt
Movie:  Ocean's 11

Conclusion

The TypeError: list indices must be integers or slices, not str occurs when we try to index the list elements using string. The list elements can be accessed using the index number (valid integer), and if it is a dictionary inside a list, we can access using the syntax list_name[index_of_dictionary]['key_within_dictionary']

List indexing is a valuable tool for you as a Python developer. You can extract specific values or ranges of values using indices or slices. You may encounter the TypeError telling you that the index of the list must be integers or slices but not strings. In this part of Python Solutions, we will discuss what causes this error and solve it with several example scenarios.


Table of contents

  • Why Does This Error Occur?
  • Iterating Over a List
    • Solution
  • Incorrect Use of List as a Dictionary
    • Solution 1: Using range() + len()
    • Solution 2: Using enumerate()
    • Solution 3: Using Python One-Liner
  • Not Converting Strings
  • Summary

Why Does This Error Occur?

Each element in a list object in Python has a distinct position called an index. The indices of a list are always integers. If you declare a variable and use it as an index value of a list element, it does not have an integer value but a string value, resulting in the raising of the TypeError.

In general, TypeError in Python occurs when you try to perform an illegal operation for a specific data type.

You may also encounter the similar error “TypeError: list indices must be integers, not tuple“, which occurs when you try to index or slice a list using a tuple value.

Let’s look at an example of a list of particle names and use indices to return a specific particle name:

particle_list = ['gluon', 'photon', 'muon', 'electron', 'Z-boson']

value = particle_list[2]

print(value)
muon

You can also use slices, which define an integer combination: start-point, end-point, and step-size, which will return a sub-list of the original list. See the slice operation performed on the particle list:

sub_list_1 = particle_list[3:5]

print(sub_list_1)
['electron', 'Z-boson']
sub_list_2 = particle_list[1:5:2]

print(sub_list_2)
['photon', 'electron']

In the second example, the third integer is the step size. If you do not specify the step size, it will be set to the default value of 1.

Iterating Over a List

When trying to iterate through the items of a list, it is easy to make the mistake of indexing a list using the list values, strings instead of integers or slices. If you try iterating over the list of particles using the particle names as indices, you will raise the TypeError

particle_list = ['gluon', 'photon', 'muon', 'electron', 'Z-boson']

for particle in particle_list:
    if particle_list[particle] == 'electron':
        print('Electron is in the list!')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      1 for particle in particle_list:
      2     if particle_list[particle] == 'electron':
      3         print('Electron is in the list!')
      4 

TypeError: list indices must be integers or slices, not str

Here, the error is raised because we are using string values as indices for the list. In this case, we do not need to index the list as the list values exist in the particle variable within the for statement.

Solution

particle_list = ['gluon', 'photon', 'muon', 'electron', 'Z-boson']

for particle in particle_list:
    if particle == 'electron':
        print('Electron is in the list!')
Electron is in the list!

We can use the if in statement to check if an item exists in a list as discussed in the Python: Check if String Contains a Substring. For example:

particle_list = ['gluon', 'photon', 'muon', 'electron', 'Z-boson']

if 'electron' in particle_list:
    print('Electron is in the list!')
Electron is in the list!

Incorrect Use of List as a Dictionary

We can treat the list of particle names to include their masses and store the values as a list of JSON objects. Each object will hold the particle name and mass. We can access the particle mass using indexing. In this example, we take the electron, muon and Z-boson:

 particles_masses = [
 {
"Name": "electron",
"Mass": 0.511
},
 {
"Name": "muon",
"Mass": 105.7
},
{
"Name": "Z-boson",
"Mass": 912000
}
]

if particles_masses["Name"] == 'muon':
    print(f'Mass of Muon is: {particles_masses["Mass"]} MeV')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      1 if particles_masses["Name"] == 'muon':
      2     print(f'Mass of Muon is: {particles_masses["Mass"]} MeV')
      3 

TypeError: list indices must be integers or slices, not str

We see the error arise because we are trying to access the dictionary using the “Name” key, but the dictionary is actually inside a list. You must first access the dictionary using its index within the list.

Solution 1: Using range() + len()

When accessing elements in a list, we need to use an integer or a slice. Once we index the list, we can use the “Name” key to get the specific element we want from the dictionary.

for i in range(len(particles_masses)):
    if particles_masses[i]["Name"] == 'muon':
        print(f'Mass of Muon is: {particles_masses["Mass"]} MeV')
Mass of Muon is: 105.7 MeV

The change made uses integer type I to index the list of particles and retrieve the particle dictionary. With access to the dictionary type, we can then use the “Name” and “Mass” keys to get the values for the particles present.

Solution 2: Using enumerate()

You can access the index of a dictionary within the list using Python’s built-in enumerate method as shown below:

for n, name in enumerate(particles_masses):

    if particles_masses[n]["Name"] == 'muon':

        print(f'Mass of Muon is: {particles_masses[n]["Mass"]} MeV')
Mass of Muon is: 105.7 MeV

Solution 3: Using Python One-Liner

A more complicated solution for accessing a dictionary is to use the search() function and list-comprehension

search = input("Enter particle name you want to explore:  ")

print(next((item for item in particles_masses if search.lower() in item ["Name"].lower()), 'Particle not found!'))
Enter particle name you want to explore:  muon
{'Name': 'muon', 'Mass': 105.7}

Not Converting Strings

You may want to design a script that takes the input to select an element from a list. The TypeError can arise if we are trying to access the list with a “string” input. See the example below:

particles_to_choose = ["electron", "muon", "Z-boson"]

chosen = input('What particle do you want to study? (0, 1, or 2)?')

print(particles_to_choose[chosen])
What particle do you want to study? (0, 1, or 2)?1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 print(particles_to_choose[chosen])

TypeError: list indices must be integers or slices, not str

The error arises because the index returned by the input() function’s default, which is “string”. To solve this, we need to convert the input chosen to an integer type. We can do this by using the int() function:

particles_to_choose = ["electron", "muon", "Z-boson"]

chosen = int(input('What particle do you want to study? (0, 1, or 2)?'))

print(particles_to_choose[chosen])
What particle do you want to study? (0, 1, or 2)?1
muon

Summary

This TypeError occurs when you try to index a list using anything other than integer values or slices. You can convert your values to integer type using the int() function. You can use the “if… in” statement to extract values from a list of strings. If you are trying to iterate over a dictionary within a list, you have to index the list using either range() + len(), enumerate() or next().

If you are encountering other TypeError issues in your code, I provide a solution for another common TypeError in the article titled: “Python TypeError: can only concatenate str (not “int”) to str Solution“.

Thanks for reading to the end of this article. Stay tuned for more of the Python Solutions series, covering common problems data scientists and developers encounter coding in Python. If you want to explore educational resources for Python in data science and machine learning, go to the Online Courses Python page for the best online courses and resources. Have fun and happy researching!

  • Type module js ошибка
  • Type mismatch vba excel ошибка runtime 13
  • Type mismatch vba access ошибка
  • Tylo cc50 ошибка 003
  • Txd workshop ошибка при открытии hud txd для gta sa