Меню

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

3 answers to this question.

df.iterrows() returns a tuple with index and the row value. So, you will have handle both the index and the value. Try this:

import pandas as pd

df = pd.read_csv(“/home/user/data1”)

for index, row in df.iterrows():
    print (row['Email'])

Hope this helps!!

If you need to learn more about Python, It’s recommended to join Python Training today.

Thanks!






answered

Mar 28, 2019


by
Jackie



iterrows() method returns a tuple of form: (index, row)

so you’d have to use row[1][‘Email’] to get what you’re looking for






answered

Jun 13, 2019


by
rahuldev



I get the following error when I try row[1][‘Email’]

TypeError: string indices must be integers, not str

Related Questions In Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import random
import sys
 
WIDTH = 8
HEIGHT = 8
 
def drawBoard(board):
    print(' 12345678')
    print(' +--------+')
    for y in range(HEIGHT):
        print('%s|' % (y+1), end='')
        for x in range(WIDTH):
            print(board[x][y], end='')
        print('%s|' % (y+1))
    print(' +--------+')
    print(' 12345678')
 
def getNewBoard():
    board = []
    for i in range(WIDTH):
        board.append([' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '])
    return board
 
def isValidMove(board, tile, xstart, ystart):
    if board[xstart][ystart] != ' ' or not isOnBoard(xstart, ystart):
        return False
 
    if tile == 'X':
        otherTile = 'O'
    else:
        otherTile = 'X'
 
    tilesToFlip = []
    for xdirection, ydirection in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]:
        x, y = xstart, ystart
        x += xdirection #Первый шаг в направлении х
        y += ydirection #Первый шаг в направлении у
        while isOnBoard(x, y) and board[x][y] == otherTile:
            x += xdirection
            y += ydirection
            if isOnBoard(x, y) and board[x][y] == tile:
                while True:
                    x -= xdirection
                    y -= ydirection
                    if x == xstart and y == ystart:
                        break
                    tilesToFlip.append([x, y])
 
    if len(tilesToFlip) == 0:
        return False
    return tilesToFlip
 
def isOnBoard(x, y):
    return x >= 0 and x <= WIDTH - 1 and y >= 0 and y <= HEIGHT - 1
 
def getBoardWithValidMoves(board, tile):
    boardCopy = getBoardCopy(board)
 
    for x, y in getValidMoves(boardCopy, tile):
        boardCopy[x][y] = '.'
    return boardCopy
 
def getValidMoves(board, tile):
    validMoves = []
    for x in range(WIDTH):
        for y in range(HEIGHT):
            if isValidMove(board, tile, x, y) != False:
                validMoves.append([x, y])
    return validMoves
 
def getScoreOfBoard(board):
    xscore = 0
    oscore = 0
    for x in range(WIDTH):
        for y in range(HEIGHT):
            if board[x][y] == 'X':
                xscore += 1
            if board[x][y] == 'O':
                oscore += 1
    return ('X ' + str(xscore), 'O ' + str(oscore))
 
def enterPlayerTile():
    tile = ''
    while not (tile == 'X' or tile == 'O'):
        print('Вы играете за Х или О???')
        tile = input().upper()
 
    if tile == 'X':
        return ['X', 'O']
    else:
        return ['O', 'X']
 
def whoGoesFirst():
    if random.randint(0, 1) == 0:
        return 'Компьютер'
    else:
        return 'Человек'
 
def makeMove(board, tile, xstart, ystart):
    tilesToFlip = isValidMove(board, tile, xstart, ystart)
 
    if tilesToFlip == False:
        return False
 
    board[xstart][ystart] = tile
    for x, y in tilesToFlip:
        board[x][y] = tile
    return True
 
def getBoardCopy(board):
    boardCopy = getNewBoard()
 
    for x in range(WIDTH):
        for y in range(HEIGHT):
            boardCopy[x][y] = board[x][y]
 
    return boardCopy
 
def isOnCorner(x, y):
    return (x == 0 or x == WIDTH - 1) and (y == 0 or y == HEIGHT - 1)
 
def getPlayerMove(board, playerTile):
    DIGITS1TO8 = '1 2 3 4 5 6 7 8'.split()
    while True:
        print('Укажите ход, текст "Выход" для завершения игры или "Подсказка" для вывода подсказки')
        move = input().lower()
        if move == 'Выход' or move == 'Подсказка':
            return move
 
        if len(move) == 2 and move[0] in DIGITS1TO8 and move[1] in DIGITS1TO8:
            x = int(move[0]) - 1
            y = int(move[1]) - 1
            if isValidMove(board, playerTile, x, y) == False:
                continue
            else:
                break
        else:
            print('Это недопустимый ход. Введите номер столбца (1-8) и номер ряда (1-8)')
            print('К примеру, 81 перемещает в верхний правый угол')
 
    return [x, y]
 
def getComputerMove(board, computerTile):
    possibleMoves = getValidMoves(board, computerTile)
    random.shuffle(possibleMoves)
 
    for x, y in possibleMoves:
        if isOnCorner(x, y):
            return [x, y]
 
    bestScore = -1
    for x, y in possibleMoves:
        boardCopy = getBoardCopy(board)
        makeMove(boardCopy, computerTile, x, y)
        score = getScoreOfBoard(boardCopy)[computerTile]
        if score > bestScore:
            bestMove = [x, y]
            bestScore = score
    return bestMove
 
def printScore(board, playerTile, computerTile):
    scores = getScoreOfBoard(board)
    print('Ваш счет: %s. Счет компьютера: %s.' % str((scores[playerTile, scores[computerTile]])))
 
def playGame(playerTile, computerTile):
    showHints = False
    turn = whoGoesFirst()
    print(turn + ' ходит первым')
 
    board = getNewBoard()
    board[3][3] = 'X'
    board[3][4] = 'O'
    board[4][3] = 'O'
    board[4][4] = 'X'
 
    while True:
        playerValidMoves = getValidMoves(board, playerTile)
        computerValidMoves = getValidMoves(board, computerTile)
 
        if playerValidMoves == [] and computerValidMoves == []:
            return board
        elif turn == 'Человек':
            if playerValidMoves != []:
                if showHints:
                    validMovesBoard = getBoardWithValidMoves(board, playerTile)
                    drawBoard(validMovesBoard)
                else:
                    drawBoard(board)
                printScore(board, playerTile, computerTile)
                move = getPlayerMove(board, playerTile)
                if move == 'Выход' or 'выход':
                    print('Благодарим за игру!')
                    sys.exit()
                elif move == 'Подсказка' or 'подсказка':
                    showHints = not showHints
                    continue
                else:
                    makeMove(board, playerTile, move[0], move[1])
            turn = 'Компьютер'
 
        elif turn == 'Компьютер':
            if computerValidMoves != []:
                drawBoard(board)
                printScore(board, playerTile, computerTile)
 
                input('Нажмите ENTER для просмотра хода компьютера')
                move = getComputerMove(board, computerTile)
                makeMove(board, computerTile, move[0], move[1])
            turn = 'Человек'
 
playerTile, computerTile = enterPlayerTile()
 
while True:
    finalBoard = playGame(playerTile, computerTile)
 
    drawBoard(finalBoard)
    scores = getScoreOfBoard(finalBoard)
    print('X набрал %s очков. О набрал %s очков.' % str((scores['X'], scores['O'])))
    if scores[playerTile] > scores[computerTile]:
        print("Вы победили компьютер, обогнав его на %s очка(ов)!" % str((scores[playerTile] - scores[computerTile])))
    elif scores[playerTile] < scores[computerTile]:
        print('Вы проиграли. Компьютер обогнал вас на %s очка(ов)' % str((scores[computerTile] - scores[playerTile])))
    else:
        print("Ничья")
input()

Hi

If i install djangocms-multisite according to the guide. I get the following traceback:

Environment:


Request Method: GET
Request URL: http://localhost:8000/

Django Version: 1.10.7
Python Version: 3.5.2
Installed Applications:
('djangocms_admin_style',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.admin',
 'django.contrib.sites',
 'django.contrib.sitemaps',
 'django.contrib.staticfiles',
 'django.contrib.messages',
 'cms',
 'menus',
 'sekizai',
 'treebeard',
 'djangocms_text_ckeditor',
 'filer',
 'easy_thumbnails',
 'djangocms_column',
 'djangocms_link',
 'cmsplugin_filer_file',
 'cmsplugin_filer_folder',
 'cmsplugin_filer_image',
 'cmsplugin_filer_utils',
 'djangocms_style',
 'djangocms_snippet',
 'djangocms_googlemap',
 'djangocms_video',
 'multisite',
 'djangocms_multisite',
 'cmsplugin_contact_plus',
 'image_gallery',
 'post_office',
 'news',
 '...')
Installed Middleware:
('multisite.middleware.DynamicSiteMiddleware',
 'cms.middleware.utils.ApphookReloadMiddleware',
 'djangocms_multisite.middleware.CMSMultiSiteMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'cms.middleware.user.CurrentUserMiddleware',
 'cms.middleware.page.CurrentPageMiddleware',
 'cms.middleware.toolbar.ToolbarMiddleware',
 'cms.middleware.language.LanguageCookieMiddleware')



Traceback:

File "/.../env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  42.             response = get_response(request)

File "/.../env/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response
  244.             response = middleware_method(request)

File "/.../env/lib/python3.5/site-packages/djangocms_multisite/middleware.py" in process_request
  17.                 urlconf = settings.MULTISITE_CMS_URLS[host]

Exception Type: TypeError at /
Exception Value: tuple indices must be integers or slices, not str

I don’t exactly know if there is something unusual with my setup, however I could fix the issue if I change the following file:
/…/env/lib/python3.5/site-packages/djangocms_multisite/middleware.py

urlconf = settings.MULTISITE_CMS_URLS[host]

to

urlconf = settings.MULTISITE_CMS_URLS[0][host]

Could this be a general error?

Kind regards
Tobias

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.

May-08-2019, 07:37 PM
(This post was last modified: May-08-2019, 09:53 PM by Yoriz.)

Hi All,
I have a requirement to port a table from MySQL database server to postgreSQL Database server.

I’m using a Magento website and its backend is MySQL,and my Datawarehouse is running on postgreSQL.My requirement is to port few table’s from source to destination,Only few columns need to be ported into a new schema in the Destination.

I’m using the below query ,Can anyone check this and guide me to perfect it.

need to load three tables or import certain Query from Magento to my data ware house in a staging table using python.

Can you suggest how this can be done?Below is the code i’m using now, it’s not a generic one, can you help me to improve this.

import psycopg2

Conn_DWH = psycopg2.connect("host=postgres dbname=Postgres user=postgres password=*** ")
Conn_Magento = psycopg2.connect("host=Magento dbname=Magento user=Magento password=*** ")
conndwh = Conn_DWH.cursor()
curmag= Conn_Magento.cursor()

cur.execute("CREATE TABLE sales_flat_quote (customer_id,entity_id,store_id,created_at,updated_at,items_count,base_row_total,row_total,base_discount_amount,base_subtotal_with_discount,base_to_global_rate,is_active);")
sql = ('INSERT INTO "sales_flat_quote" ( customer_id,entity_id,store_id,created_at,updated_at,items_count,base_row_total,row_total,base_discount_amount,base_subtotal_with_discount,base_to_global_rate,is_active) values (%s, %s,%s, %s,%s,%s, %s,%s,%s, %s,%s,%s);')
conndwh.execute('select customer_id,entity_id,store_id,created_at,updated_at,items_count,base_row_total,row_total,base_discount_amount,base_subtotal_with_discount,base_to_global_rate,is_active from "sales_flat_quote" where is_active=1;')
tempG = conndwh.fetchall()
data = (tempG)

 if data:
    curmag.execute (sql, data)
    print('data loaded to warehouse db')
  else:
    print('data is empty')

#commit transactions
Conn_DWH.commit()
Conn_Magento.commit()

#close connections
conndwh.close()
curmag.close()

Conn_DWH.close()
Conn_Magento.close()

Posts: 11,550

Threads: 445

Joined: Sep 2016

Reputation:
444

May-08-2019, 09:43 PM
(This post was last modified: May-08-2019, 09:44 PM by Larz60+.)

why not just dump it all to an sql file, then reload into PostgreSQL
(Don’t forget indexes, stored procedures, etc.

Posts: 4

Threads: 2

Joined: Apr 2019

Reputation:
0

(May-08-2019, 09:43 PM)Larz60+ Wrote: why not just dump it all to an sql file, then reload into PostgreSQL
(Don’t forget indexes, stored procedures, etc.

Hi Lars,

Thanks a lot for the reply.But I’m new to python and it’s pretty hard to understand the existing code which is using multi corn foreign data wrapper along with MySQLdb API.So is there any sample script or references which I can refer.

Both systems are using different Database systems,If there is any suggestions or sample piece of code it’ll be very much useful.

Thanks
Sandy

Posts: 8

Threads: 4

Joined: May 2019

Reputation:
0

May-09-2019, 11:07 AM
(This post was last modified: May-09-2019, 11:10 AM by buran.)

Hi All,
I have a requirement to create a staging table in our data ware house which is running on Postgres and import data from our Magento website which is using MySQL database using Python.

I have created the below query for the importing purpose,Can you please check and confirm whether this is fine? Or any alternative methods are there for doing it?
Also i want to know how we can manage the DATATYPE mismatch issues while porting?

If someone can post a sample or edit the below code it will be of great help.

import psycopg2
import os
import time
import MySQLdb
import sys
import mysql.connector
from pprint import pprint
from datetime import datetime
from psycopg2 import sql
#from utils.utils import get_global_config

def psql_command(msql, psql, msql_command, psql_command):

    msql.execute(msql_command)
    
    for row in cur_msql:
        try:
            psql.execute(command, row)
        except psycopg2.Error as e:
            print "Cannot execute the query!!", e.pgerror
            sys.exit("Some problem occured with the query!!!")

def dB_Fetch():

try:
  cnx_msql = mysql.connector.connect( host=host_mysql, user=user_mysql, passwd=pswd_mysql, db=dbna_mysql )
except mysql.connector.Error as e:
  print "MYSQL: Unable to connect!", e.msg
  sys.exit(1)

# Postgresql connection
try:
  cnx_psql = psycopg2.connect(conn_string_psql)
except psycopg2.Error as e:
  print('PSQL: Unable to connect!n{0}').format(e)
  sys.exit(1)

# Cursors initializations
cur_msql = cnx_msql.cursor(dictionary=True)
cur_psql = cnx_psql.cursor()


 try:

   print("creating table using cursor")

   SQL_create_Staging_schema="""CREATE SCHEMA IF NOT EXISTS staging AUTHORIZATION postgres;"""

   SQL_create_sales_flat_quote="""CREATE TABLE IF NOT EXISTS staging.sales_flat_quote
            (
         entity_id            BIGINT
		, store_id 	          BIGINT
		, customer_email      TEXT
		, customer_firstname  TEXT
		, customer_middlename TEXT
		, customer_lastname   TEXT
		, customer_is_guest   BIGINT
		, customer_group_id   BIGINT
		, created_at 	      TIMESTAMP WITHOUT TIME ZONE
		, updated_at 	      TIMESTAMP WITHOUT TIME ZONE
		, is_active 			BIGINT
		, items_count 			BIGINT
		, items_qty 			BIGINT
		, base_currency_code 	        TEXT
		, grand_total 			NUMERIC(12,4)
		, base_to_global_rate 	        NUMERIC(12,4)
		, base_subtotal 		NUMERIC(12,4)
		, base_subtotal_with_discount   NUMERIC(12,4)
	    )
   ;"""

   SQL_create_sales_flat_quote_item="""CREATE TABLE IF NOT EXISTS staging.sales_flat_quote_item
            (     store_id        INTEGER
		, row_total       NUMERIC
		, updated_at      TIMESTAMP WITHOUT TIME ZONE
		, qty             NUMERIC
		, sku             CHARACTER VARYING
		, free_shipping   INTEGER
		, quote_id        INTEGER
		, price 	  NUMERIC
		, no_discount 	  INTEGER
		, item_id 	  INTEGER
		, product_type 	  CHARACTER VARYING
		, base_tax_amount NUMERIC
		, product_id 	  INTEGER
		, name 		  CHARACTER VARYING
		, created_at 	  TIMESTAMP WITHOUT TIME ZONE
	    );"""

   print("Creating  Schema")   
   cur_psql.execute(SQL_create_Staging_schema)
   print("schema  succesfully created")

   print("Creating staging.sales_flat_quote table")
   cur_psql.execute(SQL_create_sales_flat_quote)
   print("staging.sales_flat_quote table  successfully created")

   print("Creating staging.sales_flat_quote_item table")
   cur_psql.execute(SQL_create_sales_flat_quote_item)
   print("staging.sales_flat_quote_item table  successfully created")
   cur_psql.commit();
   print("Fetching data from source server")

commands = [("SELECT customer_id,entity_id,store_id,created_at,updated_at,items_count,base_row_total,row_total,base_discount_amount,base_subtotal_with_discount,base_to_global_rate,is_active from sales_flat_quote where is_active=1;",
             "INSERT INTO staging.sales_flat_quote (customer_id,entity_id,store_id,created_at,updated_at,items_count,base_row_total,row_total,base_discount_amount,base_subtotal_with_discount,base_to_global_rate,is_active) 
              VALUES (%(customer_id)s, %(entity_id)s, %(store_id)s, %(created_at)s, %(updated_at)s, %(items_count)s, %(base_row_total)s, %(row_total)s, %(base_discount_amount)s, %(base_subtotal_with_discount)s, %(base_to_global_rate)s, %(is_active)s)"),
            
            ("SELECT store_id,row_total,updated_at,qty,sku,free_shipping,quote_id,price,no_discount,item_id,product_type,base_tax_amount,product_id,name,created_at from sales_flat_quote_item",
             "INSERT INTO staging.sales_flat_quote_item (store_id,row_total,updated_at,qty,sku,free_shipping,quote_id,price,no_discount,item_id,product_type,base_tax_amount,product_id,name,created_at) VALUES (%(store_id)s, %(row_total)s, %(updated_at)s, %(qty)s, %(sku)s, %(free_shipping)s, %(quote_id)s, %(price)s, %(no_discount)s, %(item_id)s, %(product_type)s, %(base_tax_amount)s, %(product_id)s, %(name)s, %(created_at)s)")
            
            ]
for msql_command, psql_command in commands:
    psql_command(cur_msql, cur_psql, msql_command, psql_command)

 except (Exception, psycopg2.Error) as error:
     print ("Error while fetching data from PostgreSQL", error)
 finally:
     ## Closing cursors
     cur_msql.close()
     cur_psql.close()
     ## Committing
     cnx_psql.commit()
     ## Closing database connections
     cnx_msql.close()
     cnx_psql.close()
      
if __name__ == '__main__':
    dB_Fetch()

Posts: 8

Threads: 4

Joined: May 2019

Reputation:
0

Hi
I have re-edited my PY script,Can you please tell me how can i deal with DATA TYPE matching and any how if this can be improved?
Please suggest.

import psycopg2
import os
import time
import MySQLdb
import sys
import mysql.connector
from pprint import pprint
from datetime import datetime
from psycopg2 import sql

from utils.postgres import get_connection
from utils.utils import get_global_config


def psql_command(msql, psql, msql_command, psql_command):

    msql.execute(msql_command)
    
    for row in cur_msql:
        try:
            psql.execute(command, row)
        except psycopg2.Error as e:
            print "Cannot execute the query!!", e.pgerror
            sys.exit("Some problem occured with the query!!!")



def dB_Fetch():

  # Read all connection information from config.ini
    config = get_config_object()
try:
  cnx_msql = get_db_connection("magento")
except mysql.connector.Error as e:
  print "MYSQL: Unable to connect!", e.msg
  sys.exit(1)

# Postgresql connection
try:

  cnx_psql = get_connection(get_global_config(), 'pg_dwh')#get_db_connection("pg_dwh")
  #cnx_psql = psycopg2.connect(conn_string_psql)
except psycopg2.Error as e:
  print('PSQL: Unable to connect!n{0}').format(e)
  sys.exit(1)

# Cursors initializations
cur_msql = cnx_msql.cursor(dictionary=True)
cur_psql = cnx_psql.cursor()

 try:

   print("creating table using cursor")

   SQL_create_Staging_schema="""CREATE SCHEMA IF NOT EXISTS staging AUTHORIZATION postgres;"""

   SQL_create_sales_flat_quote="""CREATE TABLE IF NOT EXISTS staging.sales_flat_quote
            (
        entity_id             BIGINT
		, store_id 	          BIGINT
		, customer_email      TEXT
		, customer_firstname  TEXT
		, customer_middlename TEXT
		, customer_lastname   TEXT
		, customer_is_guest   BIGINT
		, customer_group_id   BIGINT
		, created_at 	      DATETIME
		, updated_at 	      DATETIME
		, is_active 			BIGINT
		, items_count 			BIGINT
		, items_qty 			BIGINT
		, base_currency_code 	TEXT
		, grand_total 			NUMERIC(12,4)
		, base_to_global_rate 	NUMERIC(12,4)
		, base_subtotal 		NUMERIC(12,4)
		, base_subtotal_with_discount   NUMERIC(12,4)
	    )
   ;"""

   SQL_create_sales_flat_quote_item="""CREATE TABLE IF NOT EXISTS staging.sales_flat_quote_item
    (     store_id        INTEGER
		, row_total       NUMERIC
		, updated_at      DATETIME
		, qty             NUMERIC
		, sku             CHARACTER VARYING
		, free_shipping   INTEGER
		, quote_id        INTEGER
		, price 	      NUMERIC
		, no_discount 	  INTEGER
		, item_id 	      INTEGER
		, product_type 	  CHARACTER VARYING
		, base_tax_amount NUMERIC
		, product_id 	  INTEGER
		, name 		      CHARACTER VARYING
		, created_at 	  DATETIME
	    );"""
   cur_psql.execute(SQL_create_Staging_schema)

   cur_psql.execute(SQL_create_sales_flat_quote)

   cur_psql.execute(SQL_create_sales_flat_quote_item)
   cur_psql.commit();


    
commands = [("SELECT customer_id,entity_id,store_id,created_at,updated_at,items_count,base_row_total,row_total,base_discount_amount,base_subtotal_with_discount,base_to_global_rate,is_active from sales_flat_quote where is_active=1;",
             "INSERT INTO staging.sales_flat_quote (customer_id,entity_id,store_id,created_at,updated_at,items_count,base_row_total,row_total,base_discount_amount,base_subtotal_with_discount,base_to_global_rate,is_active) 
              VALUES (%(customer_id)s, %(entity_id)s, %(store_id)s, %(created_at)s, %(updated_at)s, %(items_count)s, %(base_row_total)s, %(row_total)s, %(base_discount_amount)s, %(base_subtotal_with_discount)s, %(base_to_global_rate)s, %(is_active)s)"),
            
            ("SELECT store_id,row_total,updated_at,qty,sku,free_shipping,quote_id,price,no_discount,item_id,product_type,base_tax_amount,product_id,name,created_at from sales_flat_quote_item",
             "INSERT INTO staging.sales_flat_quote_item (store_id,row_total,updated_at,qty,sku,free_shipping,quote_id,price,no_discount,item_id,product_type,base_tax_amount,product_id,name,created_at) VALUES (%(store_id)s, %(row_total)s, %(updated_at)s, %(qty)s, %(sku)s, %(free_shipping)s, %(quote_id)s, %(price)s, %(no_discount)s, %(item_id)s, %(product_type)s, %(base_tax_amount)s, %(product_id)s, %(name)s, %(created_at)s)"),
            
            ("SELECT select created_at,url_path,price,short_description,url_key,thumbnail_label,small_image,thumbnail,name,sku,type_id from catalog_product_flat_1", 
             "INSERT INTO staging.catalog_product_flat_1 (created_at,url_path,price,short_description,url_key,thumbnail_label,small_image,thumbnail,name,sku,type_id) 
              VALUES (%(created_at)s, %(url_path)s, %(price)s, %(short_description)s, %(url_key)s, %(thumbnail_label)s, %(small_image)s, %(thumbnail)s, %(name)s, %(sku)s, %(type_id)s)"),
            
            ]

for msql_command, psql_command in commands:
    psql_command(cur_msql, cur_psql, msql_command, psql_command)

 except (Exception, psycopg2.Error) as error:
     print ("Error while fetching data from PostgreSQL", error)
 finally:
     ## Closing cursors
     cur_msql.close()
     cur_psql.close()
     ## Committing
     cnx_psql.commit()
     ## Closing database connections
     cnx_msql.close()
     cnx_psql.close()

        
if __name__ == '__main__':
    dB_Fetch()

Posts: 8

Threads: 4

Joined: May 2019

Reputation:
0

May-10-2019, 01:55 PM
(This post was last modified: May-10-2019, 01:55 PM by Sandy7771989.)

Hi All,
I’m getting the below error while i’m calling my function,Does anyone have any suggestions on how to deal with it? I want to insert the selected data into the destination table with the insert command.

Quote:Error while fetching data from PostgreSQL tuple indices must be integers or slices, not str

Sub Function:

def psql_func(msql, psql, msql_command, psql_command):
    print("function call")
    msql.execute(msql_command)
    print(" ggg call")    
    for row in msql:
        try:
            print ("query!!")
            print(row[0])
            print(psql_command)
            psql.execute(psql_command, row)
            print (" execute  query!!")
        except psycopg2.Error as e:
            print ("Cannot execute the query!!", e.pgerror)
            
            sys.exit("Some problem occured with the query!!!")


#Main Function


def dB_Fetch():
 try:
   cnx_msql = psycopg2.connect(user="sandy",
                                  password="postgres",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="clone")
 except mysql.connector.Error as e:
   print ("MYSQL: Unable to connect!", e.msg)
   sys.exit(1)

# Postgresql connection
 try:
   cnx_psql = psycopg2.connect(user="sandy",
                                  password="postgres",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres")
  #cnx_psql = psycopg2.connect(conn_string_psql)
 except psycopg2.Error as e:
   print('PSQL: Unable to connect!n{0}').format(e)
   sys.exit(1)

# Cursors initializations
 cur_msql = cnx_msql.cursor()
 cur_psql = cnx_psql.cursor()

 try:
   SQL_create_Staging_schema="""CREATE SCHEMA IF NOT EXISTS staging AUTHORIZATION postgres;"""
   SQL_create_Staging_schema_clone="""CREATE SCHEMA IF NOT EXISTS clone AUTHORIZATION postgres;"""

   SQL_create_sales_flat_quote="""CREATE TABLE IF NOT EXISTS staging.sales_flat_quote
        ( customer_id          BIGINT
         , entity_id           BIGINT
		, store_id 	           BIGINT
		, customer_email      TEXT
		, customer_firstname  TEXT
		, customer_middlename TEXT
		, customer_lastname   TEXT
		, customer_is_guest   BIGINT
		, customer_group_id   BIGINT
		, created_at 	      TIMESTAMP WITHOUT TIME ZONE
		, updated_at 	      TIMESTAMP WITHOUT TIME ZONE
		, is_active 			BIGINT
		, items_count 			BIGINT
		, items_qty 			BIGINT
		, base_currency_code 	TEXT
		, grand_total 			NUMERIC(12,4)
		, base_to_global_rate 	NUMERIC(12,4)
		, base_subtotal 		NUMERIC(12,4)
		, base_subtotal_with_discount   NUMERIC(12,4)
	    )
   ;"""

   SQL_create_sales_flat_quote_clone=""" same structure as above table """
   SQL_create_sales_flat_quote_item="""CREATE TABLE IF NOT EXISTS staging.sales_flat_quote_item
            (     store_id        INTEGER
		, row_total       NUMERIC
		, updated_at      TIMESTAMP WITHOUT TIME ZONE
		, qty             NUMERIC
		, sku             CHARACTER VARYING
		, free_shipping   INTEGER
		, quote_id        INTEGER
		, price 	  NUMERIC
		, no_discount 	  INTEGER
		, item_id 	  INTEGER
		, product_type 	  CHARACTER VARYING
		, base_tax_amount NUMERIC
		, product_id 	  INTEGER
		, name 		  CHARACTER VARYING
		, created_at 	  TIMESTAMP WITHOUT TIME ZONE
	    );"""

   SQL_create_sales_flat_quote_item_clone="""same structure as above"""
   
   INS1="INSERT INTO clone.sales_flat_quote (customer_id, entity_id, store_id, customer_email , customer_firstname, customer_middlename, customer_lastname , customer_is_guest, customer_group_id, created_at, updated_at, is_active, items_count, items_qty, base_currency_code, grand_total, base_to_global_rate, base_subtotal, base_subtotal_with_discount) 
              VALUES (1, 1, 3, '[email protected]','sss','dddd','rrr',1,1,now(), now(), 4,67, 78, 888, 690, 1, 1,1)"

   INS2="INSERT INTO clone.sales_flat_quote_item (store_id,row_total,updated_at,qty,sku,free_shipping,quote_id,price,no_discount,item_id,product_type,base_tax_amount,product_id,name,created_at) VALUES (789999, 222, now(), 3, '33', 1, 222111, 22, 2, 2, 2, 2, 3,'sasy', now())"
       
   cur_psql.execute(SQL_create_Staging_schema)
   cur_psql.execute(SQL_create_Staging_schema_clone)
   cnx_psql.commit();
   cur_psql.execute(SQL_create_sales_flat_quote)
   print("table 1")
   cur_psql.execute(SQL_create_sales_flat_quote_item)
   print("table 2")
   cur_psql.execute(SQL_create_catalog_product_flat_1)

   cnx_psql.commit();   
   cur_psql.execute(SQL_create_sales_flat_quote_clone)
   cur_psql.execute(SQL_create_sales_flat_quote_item_clone)
   print("schema created")
   cur_psql.execute(INS1)
   print("inserted to clone1 ")
   cur_psql.execute(INS2)  
   print("inserted to clone2 ")
   #cur_psql.commit();

   commands = [("SELECT customer_id, entity_id, store_id, customer_email , customer_firstname, customer_middlename, customer_lastname , customer_is_guest, customer_group_id, created_at, updated_at, is_active, items_count, items_qty, base_currency_code, grand_total, base_to_global_rate, base_subtotal, base_subtotal_with_discount from clone.sales_flat_quote where is_active=1 AND items_count != '0' AND updated_at > '2019-05-09 00:00:00';",
             "INSERT INTO staging.sales_flat_quote (customer_id, entity_id, store_id, customer_email , customer_firstname, customer_middlename, customer_lastname , customer_is_guest, customer_group_id, created_at, updated_at, is_active, items_count, items_qty, base_currency_code, grand_total, base_to_global_rate, base_subtotal, base_subtotal_with_discount) 
              VALUES (%(customer_id)s, %(entity_id)s, %(store_id)s,%(customer_email)s,%(customer_firstname)s,%(customer_firstname)s,%(customer_middlename)s,%(customer_lastname)s,%(customer_is_guest)s, %(customer_group_id)s, %(created_at)s, %(updated_at)s, %(is_active)s, %(items_count)s, %(items_qty)s, %(base_currency_code)s, %(grand_total)s, %(base_to_global_rate)s, %(base_subtotal)s, %(base_subtotal_with_discount)s)"),
            
            ("SELECT store_id,row_total,updated_at,qty,sku,free_shipping,quote_id,price,no_discount,item_id,product_type,base_tax_amount,product_id,name,created_at from clone.sales_flat_quote_item WHERE updated_at > '2019-05-09 00:00:00'",
             "INSERT INTO staging.sales_flat_quote_item (store_id,row_total,updated_at,qty,sku,free_shipping,quote_id,price,no_discount,item_id,product_type,base_tax_amount,product_id,name,created_at) VALUES (%(store_id)s, %(row_total)s, %(updated_at)s, %(qty)s, %(sku)s, %(free_shipping)s, %(quote_id)s, %(price)s, %(no_discount)s, %(item_id)s, %(product_type)s, %(base_tax_amount)s, %(product_id)s, %(name)s, %(created_at)s)")
            ]

   for msql_command, psql_command in commands:
       psql_func(cur_msql, cur_psql, msql_command, psql_command)
 
 except (Exception, psycopg2.Error) as error:
     print ("Error while fetching data from PostgreSQL", error)
 finally:
     ## Committing
     cnx_psql.commit()
     ## Closing database connections
     cnx_msql.close()
     cnx_psql.close()

if __name__ == '__main__':
    dB_Fetch()

Posts: 4

Threads: 2

Joined: Apr 2019

Reputation:
0

May-12-2019, 11:41 AM
(This post was last modified: May-12-2019, 11:42 AM by Sandy777.)

Hi Al,
I’m getting the below error while running my script,I’m trying to port data from MySQLdb to postgreSQL Database.

If anyone have any idea on what this error is and how to resolve it,Kindly let me know?

Quote:Error while fetching data from PostgreSQL tuple indices must be integers or slices, not str

##Sub function
def psql_func(msql, psql, msql_command, psql_command):
    print("function call")
    msql.execute(msql_command)
    print(" ggg call")    
    for row in msql:
        try:
            print ("query!!")
            print(row[0])
            print(psql_command)
            psql.execute(psql_command, row)
            print (" execute  query!!")
        except psycopg2.Error as e:
            print ("Cannot execute the query!!", e.pgerror)
             
            sys.exit("Some problem occured with the query!!!")

##Part of Main function
commands = [("SELECT customer_id, entity_id, store_id, customer_email , customer_firstname, customer_middlename, customer_lastname , customer_is_guest, customer_group_id, created_at, updated_at, is_active, items_count, items_qty, base_currency_code, grand_total, base_to_global_rate, base_subtotal, base_subtotal_with_discount from clone.sales_flat_quote where is_active=1 AND items_count != '0' AND updated_at > '2019-05-09 00:00:00';",
             "INSERT INTO staging.sales_flat_quote (customer_id, entity_id, store_id, customer_email , customer_firstname, customer_middlename, customer_lastname , customer_is_guest, customer_group_id, created_at, updated_at, is_active, items_count, items_qty, base_currency_code, grand_total, base_to_global_rate, base_subtotal, base_subtotal_with_discount) 
              VALUES (%(customer_id)s, %(entity_id)s, %(store_id)s,%(customer_email)s,%(customer_firstname)s,%(customer_firstname)s,%(customer_middlename)s,%(customer_lastname)s,%(customer_is_guest)s, %(customer_group_id)s, %(created_at)s, %(updated_at)s, %(is_active)s, %(items_count)s, %(items_qty)s, %(base_currency_code)s, %(grand_total)s, %(base_to_global_rate)s, %(base_subtotal)s, %(base_subtotal_with_discount)s)"),
             
            ("SELECT store_id,row_total,updated_at,qty,sku,free_shipping,quote_id,price,no_discount,item_id,product_type,base_tax_amount,product_id,name,created_at from clone.sales_flat_quote_item WHERE updated_at > '2019-05-09 00:00:00'",
             "INSERT INTO staging.sales_flat_quote_item (store_id,row_total,updated_at,qty,sku,free_shipping,quote_id,price,no_discount,item_id,product_type,base_tax_amount,product_id,name,created_at) VALUES (%(store_id)s, %(row_total)s, %(updated_at)s, %(qty)s, %(sku)s, %(free_shipping)s, %(quote_id)s, %(price)s, %(no_discount)s, %(item_id)s, %(product_type)s, %(base_tax_amount)s, %(product_id)s, %(name)s, %(created_at)s)")
            ]
 
   for msql_command, psql_command in commands:
       psql_func(cur_msql, cur_psql, msql_command, psql_command

Table of Contents

  • ◈ Overview
  • ◈ What Is TypeError in Python?
  • ◈ Reason Behind – TypeError: List Indices Must Be Integers Or Slices, Not ‘Str’
  • ◈ Example: Trying To Access A Value Of A List of Dictionaries Using A String
    • ✨ Solution 1: Accessing Index Using range() + len()
    • ✨ Solution 2: Accessing Index Using enumerate()
    • ✨ Solution 3: Python One-Liner
  • ◈ A Simple Example
  • Conclusion

◈ Overview

Aim: How to fix – TypeError: list indices must be integers or slices, not str in Python?

Example: Take a look at the following code which generates the error mentioned above.

list1 = [‘Mathematics’,‘Physics’, ‘Computer Science’]

index = ‘1’

print(‘Second Subject: ‘, list1[index])

Output:

Traceback (most recent call last):
File “D:/PycharmProjects/pythonProject1/error.py”, line 3, in
print(‘Second Subject: ‘, list1[index])
TypeError: list indices must be integers or slices, not str

Reason:

We encountered the TypeError because we tried to access the index of the list using a string which is not possible!

Before proceeding further let’s have a quick look at the solution to the above error.

Solution:

You should use an integer to access an element using its index.

list1 = [‘Mathematics’,‘Physics’, ‘Computer Science’]

index = 1

print(‘Second Subject: ‘, list1[index])

# Output:-

# First Subject:  Physics

But this brings us to a number of questions. Let’s have a look at them one by one.

◈ What Is TypeError in Python?

TypeError is generally raised when a certain operation is applied to an object of an incorrect type.

Example:

Output:

TypeError: can only concatenate str (not “int”) to str

In the above code, we tried to add a string object and an integer object using the + operator. This is not allowed; hence we encountered a TypeError.

There can be numerous reasons that lead to the occurrence of TypeError. Some of these reasons are:

  • Trying to perform an unsupported operation between two types of objects.
  • Trying to call a non-callable caller.
  • Trying to iterate over a non-iterative identifier.

Python raises TypeError: List Indices Must Be Integers Or Slices, Not 'Str' whenever you try to access a value or an index of a list using a string.

Let us have a look at another complex example where you might encounter this kind of TypeError.

◈ Example: Trying To Access A Value Of A List of Dictionaries Using A String

Problem: Given a list of dictionaries; Each dictionary within the list contains the name of an athlete and the sports he is associated with. You have to help the user with the sports when the user enters the athletes name.

Your Code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

athletes = [

        {

            ‘name’: «Mike Tyson»,

            ‘sports’: «Boxing»

        },

        {

            ‘name’: «Pele»,

            ‘sports’: «Football»

        },

        {

            ‘name’: «Sachin Tendulkar»,

            ‘sports’: «Cricket»

        },

        {

            ‘name’: «Michael Phelps»,

            ‘sports’: «Swimming»

        },

        {

            ‘name’: «Roger Federer»,

            ‘sports’: «Tennis»

        }

]

search = input(‘Enter the name of the athlete to find his sport: ‘)

for n in range(len(athletes)):

    if search.lower() in athletes[‘Name’].lower():

        print(‘Name: ‘,athletes[‘Name’])

        print(‘Sports: ‘, athletes[‘Name’])

        break

else:

    print(‘Invalid Entry!’)

Output:

Traceback (most recent call last):
File “D:/PycharmProjects/pythonProject1/TypeError part2.py”, line 25, in
if search.lower() in athletes[‘Name’].lower():
TypeError: list indices must be integers or slices, not str

Explanation: The above error occurred because you tried to access Name using the key. The entire data-structure in this example is a list that contains dictionaries and you cannot access the value within a particular dictionary of the list using it’s key.

Solution 1: Accessing Index Using range() + len()

To avoid TypeError: list indices must be integers or slices, not str in the above example you must first access the dictionary using it’s index within the list that contains the search value and then access the value using its key.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

athletes = [

        {

            ‘name’: «Mike Tyson»,

            ‘sports’: «Boxing»

        },

        {

            ‘name’: «Pele»,

            ‘sports’: «Football»

        },

        {

            ‘name’: «Sachin Tendulkar»,

            ‘sports’: «Cricket»

        },

        {

            ‘name’: «Michael Phelps»,

            ‘sports’: «Swimming»

        },

        {

            ‘name’: «Roger Federer»,

            ‘sports’: «Tennis»

        }

]

search = input(‘Enter the name of the athlete to find his sport: ‘)

for n in range(len(athletes)):

    if search.lower() in athletes[n][‘name’].lower():

        print(‘Name: ‘,athletes[n][‘name’])

        print(‘Sports: ‘, athletes[n][‘sports’])

        break

else:

    print(‘Invalid Entry!’)

Output:

Enter the name of the athlete to find his sport: Sachin

Name:  Sachin Tendulkar

Sports:  Cricket

Explanation:

  • Instead of directly iterating over the list, you should iterate through each dictionary one by one within the list using the len() and range() methods.
  • You can access a particular value from a particular dictionary dictionary using the following syntax:
    • list_name[index_of_dictionary]['Key_within_dictionary']
    • example:- athletes[n]['name']

Solution 2: Accessing Index Using enumerate()

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

athletes = [

        {

            ‘name’: «Mike Tyson»,

            ‘sports’: «Boxing»

        },

        {

            ‘name’: «Pele»,

            ‘sports’: «Football»

        },

        {

            ‘name’: «Sachin Tendulkar»,

            ‘sports’: «Cricket»

        },

        {

            ‘name’: «Michael Phelps»,

            ‘sports’: «Swimming»

        },

        {

            ‘name’: «Roger Federer»,

            ‘sports’: «Tennis»

        }

]

search = input(‘Enter the name of the athlete to find his sport: ‘)

for n,name in enumerate(athletes):

    if search.lower() in athletes[n][‘name’].lower():

        print(‘Name: ‘,athletes[n][‘name’])

        print(‘Sports: ‘, athletes[n][‘sports’])

        break

else:

    print(‘Invalid Entry!’)

Output:

Enter the name of the athlete to find his sport: Tyson

Name:  Mike Tyson

Sports:  Boxing

Solution 3: Python One-Liner

Though this might not be the simplest of solutions or even the most Python way of resolving the issue but it deserves to be mentioned because it’s a great trick to derive your solution in a single line of code.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

athletes = [

        {

            ‘name’: «Mike Tyson»,

            ‘sports’: «Boxing»

        },

        {

            ‘name’: «Pele»,

            ‘sports’: «Football»

        },

        {

            ‘name’: «Sachin Tendulkar»,

            ‘sports’: «Cricket»

        },

        {

            ‘name’: «Michael Phelps»,

            ‘sports’: «Swimming»

        },

        {

            ‘name’: «Roger Federer»,

            ‘sports’: «Tennis»

        }

]

search = input(‘Enter the name of the athlete to find his sport: ‘)

print(next((item for item in athletes if search.lower() in item[«name»].lower()), ‘Invalid Entry!’))

Solutions:

Enter the name of the athlete to find his sport: Roger

{‘name’: ‘Roger Federer’, ‘sports’: ‘Tennis’}

◈ A Simple Example

In case you were intimidated by the above example, here’s another example for you that should make things crystal clear.

Problem: You have a list containing names, and you have to print each name with its index.

Your Code:

li = [«John», «Rock», «Brock»]

i = 1

for i in li:

    print(i, li[i])

Output:

Traceback (most recent call last):

  File «D:/PycharmProjects/pythonProject1/TypeError part2.py», line 4, in <module>

    print(i, li[i])

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

Solution:

In the above code the variable i represents an item inside the list and not an index. Therefore, when you try to use it as an index within the for loop it leads to a TypeError: list indices must be integers or slices, not str.

To avoid this error, you can either use the enumerate() function or the len() method along with the range() method as shown in the solution below.

li = [«John», «Rock», «Brock»]

print(«***SOLUTION 1***»)

# using range()+len()

for i in range(len(li)):

    print(i + 1, li[i])

print(«***SOLUTION 2***»)

# using enumerate()

for i, item in enumerate(li):

    print(i + 1, item)

Output:

***SOLUTION 1***

1 John

2 Rock

3 Brock

***SOLUTION 2***

1 John

2 Rock

3 Brock

Conclusion

We have come to the end of this comprehensive guide to resolve TypeError: List Indices Must Be Integers Or Slices, Not 'Str'. I hope this article helped clear all your doubts regarding TypeError: list indices must be integers or slices, not str and you can resolve them with ease in the future.

Please stay tuned and subscribe for more exciting articles. Happy learning! 📚

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Tumblr ошибка при загрузке форм
  • Tsa ошибка хонда crv