'int' object is not subscriptable yet all associated variables are fine [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I seem to have a line of code with an object not subscribable fault but all items in the equate check out individually. The equation that gives me the problem is this
oRetVal['Assay'] = tRS2[oCSNo_dx[aRow[oFields_dx['CycleRef']]][oFields_dx['Assay']]]
tRS2 = a recordset returned from an sqlite database as a tuple
oCSNo_dx = an object used as an index
aRow = an array of values representing a single row from a db table
oFields_dx = another object used as an index
On the lines immediately prior to this error line I run the following tests.
print(oCSNo_dx[aRow[oFields_dx['CycleRef']]]) # get 1
print(oFields_dx['Assay']) # get 21
print(tRS2[1][21]) # get 0.0
print(tRS2[1]) # get single recordset (correct one) as expected
print(tRS2[oCSNo_dx[aRow[oFields_dx['CycleRef']]]][oFields_dx['Assay']]) # get 0.0
oRetVal['Assay']=0.0 # No Fault
oRetVal['Assay']=tRS2[1][21] # No fault
print(oRetVal['Assay']) # get 0.0
From the tests oRetVal['Assay'] should take the value 0.0 from tRS2[1][21] in the full equation but it gives me the error. Just to be sure I ran the following and no error was raised ..
s = oCSNo_dx[aRow[oFields_dx['CycleRef']]]
p = oFields_dx['Assay']
oRetVal['Assay']=tRS2[s][p]
I have gone with this for now but I would dearly like to know why I couldn't do the one liner in case this is a syntax thing and I come across it again. Idea's anyone?

Your square brackets are in the wrong place. You're not looking up tRS2[1][21], but tRS2[1[21]], hence the error. It should be:
tRS2[oCSNo_dx[aRow[oFields_dx['CycleRef']]]][oFields_dx['Assay']]
But really, don't do it like this; it's impossible to debug, as you have found. Set some intermediate variables and use them in the lookup.

Related

Getting TypeError: 'int' object is not subscriptable [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
def hourglassSum():
for i in range(0,6):
arr1=map(int,input().split())
arr=list(arr1)
sum=[]
for i in range(len(arr)-2):
for j in range(len(arr)-2):
sum.append(arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2])
maxi=max(sum)
print(maxi)
hourglassSum()
This code shows the following error:
TypeError: 'int' object is not subscriptable
How to fix it?
I suspect that's what you're looking for:
def hourglassSum():
arr = []
for i in range(0,6):
arr1=map(int,input().split())
arr.append(list(arr1))
sum=[]
for i in range(len(arr)-2):
for j in range(min(len(arr[i]), len(arr[i+1]), len(arr[i+2]))-2):
sum.append(arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2])
maxi=max(sum)
print(maxi)
Two notes:
(1) you want to persist each iteration of the first loop, what you were doing was just overwriting your variable with each iteration
(2) while iterating across different elements of elements of your base list - always make sure you won't run into index out of bounds exception - I presume your approach was to put in 6x6 elements - so it's just to mitigate eventual discrepancies

'dict' object has no attribute 'value' but I see it in the dictionary when I print it out [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
When I run this line of code: print(response.keys());
I get this response: dict_keys(['#odata.context', 'value'])
When I run this line of code: print(response.value);
I get this response: AttributeError: 'dict' object has no attribute 'value'
When I print out the entire dictionary I see the attribute value. Below is what part of it printed out. I can clearly see value as an attribute.
{'#odata.context': '$metadata#Property(ListPrice,YearBuilt,ListingKey)', 'value': [{'ListPrice': 895000.0, 'YearBuilt': 0, 'ListingKey': '1000006'}, {'ListPrice': 84800.0, 'YearBuilt': 0, 'ListingKey': '1000096'}
Any ideas what is happening?
The dictionary's member function is called .values() and not .value. You missed the s and the brackets.
Try:
print(resonse.values())
Or try to access the element:
print(response['value'])
Where value happens to be a dictionary key. Obviously, this might be confusing.
You are trying to access the dict elements as an attribute response.value.
In Python to access a dictionary’s keys is by using square brackets, in your case it will be:
response['value']

Pandas error: String indices must be integers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am not sure where I went wrong with my below code, where I used two for loops to firstly iterate statename and then iterate each dictionary that contains that specific statename.
I finally resolved this via my second code (the right code on the snip) however would be keen to know why the first didn't work.
The file used is a census file with statename, countyname (a subdivision of the state) and population being the columns.
Couldn't work with the following snip (on the left) where the error is 'string indices must be integers':
As others have already suggested, please read up on providing a Minimal, Reproducible Example. Nevertheless, I can see what went wrong here. When you loop through for d in census_df, this actually loops through the column names for your data frame, i.e. SUMLEV, REGION etc. This is presumably not what you had in mind.
Then your next line if d['STNAME']==c causes an error, as the message says, because string indices must be integers. In this instance you are trying to index a string using another string STNAME.
If you really want that first method to work, try using iterrows:
state_unique=census_df['STNAME'].unique()
list=[]
def answer_five():
for c in state_unique:
count=0
for index, row in census_df.iterrows():
if row['STNAME']==c:
count+=1
list.append(count)
return(max(list))
answer_five()
Don't know why the pic is not coming up...sorry first timer here!
the first code that I tried which I have questions over are: (regarding string indices must be integers):
state_unique=census_df['STNAME'].unique()
list=[]
def answer_five():
for c in state_unique:
count=0
for d in census_df:
if d['STNAME']==c:
count+=1
return list.append(count)
answer_five()
The second code helped resolve my question is:
max_county=[]
state_unique=census_df['STNAME'].unique()
def answer_five():
for c in state_unique:
df1=census_df[census_df['STNAME']==c]
max_county.append(len(df1))
return max(max_county)
answer_five()

Look up for a value in a csv file [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I need to look up a value in a csv file given a criteria in a function. When I run my program I get all the values but not the one associated with my entry. Any help will be appreciated.
The date looks something like this:
rose,7.95
lily,3.95
begonia,5.95
The function I created is:
def problem3_8(csv_pricefile, flower):
import csv
archivo = open(csv_pricefile)
for row in csv.reader(archivo):
if flower in row[0]:
print(row[1])
archivo.close()
When I ran the program using the next line:
problem3_7("flowers.csv","rose")
I get all the value in the file, like this:
7.95
3.95
5.95
But the answer should be just the value associated with the second entry.
7.95
Thanks
I ran your code given and had the correct output of 7.95.
Is it possible you called the wrong function? In your question you referred to the function problem3_7 instead of the function problem3_8

Why does my python for loop return the same first value X times rather than unique values? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm querying a Postgres database (nfldb for anyone familiar) from Python and would like to make one of my query criteria a variable to streamline my data collection. The code I'm using
import nfldb
db = nfldb.connect()
q = nfldb.Query(db)
for i in range (1,15):
q.game(season_year=2015, season_type='Regular', week=i)
q.player(full_name='Julian Edelman')
print p.player.full_name, p.receiving_yds, p.receiving_tds
I would expect this to return each week's stats, but it returns the first week's stats 14 times. When I change week = i to explicit numbers, it returns the stats as I would expect. Why might this be happening?
Your question here will be difficult for anyone not familiar with nfldb to answer because the .game nomenclature is a special feature of nfldb that can be used to further filter your query q.
By narrowing the scope of your query to a single week, you are giving nfldb permission to discard all other non-fitting data. So when you repeat your loop and ask for the next week, you are asking for data that you just told nfldb to discard from q.
If you want to make the same query over each week individually, you will need to tuck your q = nfldb.Query(db) into the for loop so as to reset the expectation that the query starts with all data in the database available to it.
import nfldb
db = nfldb.connect()
for i in range (1,15):
q = nfldb.Query(db)
q.game(season_year=2015, season_type='Regular', week=i)
q.player(full_name='Julian Edelman')
As someone else mentioned, though, you are missing something from this codeblock since p appears out of nowhere.

Categories