how to fix 'int' object is not subscriptable error? - python

So I'm getting the error in the title when trying to print out a value from a sublist
for record in data:
(product_id, name, price) = record
accumulator = 0
order_items = ''
if 'order_1' in form:
print('<tr><td>%s</td><td>%s</td>' % (name[0], price[0]))
accumulator += int(price[0])
order_items += 'item 1 (check menu), '
I just want the output to be a print of those values, while adding on the the accumulator variables, any help would be much appreciated.

The reason is this part:
for record in data:
(product_id, name, price) = record
You're probably expecting product_id, name and price to be the "columns" corresponding to sub-collections in data, but that is not how it works. Instead, they just take the value of the last sub-collectiong in data.
You need something like this, which turns data into a nested collection where each sub-collection can be treated as a single column:
product_id, name, price = zip(*data)
The iterative equivalent:
product_id = []
name = []
price = []
for record in data:
product_id.append(record[0])
name.append(record[1])
price.append(record[2])
The rest of your code should work fine, except for one correction I would suggest; instead of using C-style formatting, prefer f-strings (Python >= 3.6) or format method formatting:
output = f'<tr><td>{name[0]}</td><td>{price[0]}</td>' # Python >= 3.6
output = '<tr><td>{}</td><td>{}</td>'.format(name[0], price[0]) # others

Related

int() argument must be a string, a bytes-like object or a number, not 'tuple' will using sql formating in python

I am making a code to add an item to a database, however, I get the error
int() argument must be a string, a bytes-like object or a number, not 'tuple'
as I am trying to turn the information you get from a tuple when using the fetchall() function in python (i.e. (1,),(2,),(3,) into an int, however I do not know how to do this. Here is the code I am working on.
try:
adding_item_name = input("What would you like to name the item to be? >>> ")
adding_item_value = input("What would you like the value of the item to be? >>> ")
adding_item_quantity = int(input("What would you like the quantity to be? >>> "))
cursor.execute('SELECT item_ID FROM Items_in_stock ORDER BY item_ID')
adding_item_ID = int(cursor.fetchall()[-1])
adding_item_ID += 1
print(adding_item_ID)
print(adding_item_ID2)
cursor.execute('INSERT INTO Items_in_stock (item_ID, item_name, item_value, item_quantity) VALUES (?,?,?,?)',
(adding_item_ID_int, adding_item_name, adding_item_value, adding_item_quantity,))
print("Added item successfully")
except Exception as e:
print(str(e))
print("Unable to add item")
I have tried to do this:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
but to no avail.
Each query always produces a tuple of results, no matter how many fields the SELECT statement requests, so that the API is not dependent on the particular argument to execute.
Likewise, fetchall returns a list of results, so that the API doesn't change depending on whether the query produces 0, 1, or more results.
So you need to index cursor.fetchall() twice: once to get the last (and only?) element of the result, and once to get the only value in tuple.
adding_item_ID = int(cursor.fetchall()[-1][0])
It's possible you could refine the query to avoid needing fetchall. Use something like
cursor.execute('SELECT max(item_ID) FROM Items_in_stock ORDER BY item_ID')
and then you can use
adding_item_ID = int(cursor.fetchone()[0])
This will be more efficient as well, as the work of selecting the largest item id is done in the database, not in Python, and only one result has to be retrieved.
you can try this:
adding_item_ID = cursor.fetchall()[-1][0] # get the first element of the tuple
adding_item_ID = int(adding_item_ID) # convert to int
you can also use a for loop to iterate over the tuple and convert each element to an integer:
for item_id in cursor.fetchall():
item_id = int(item_id[0])

TypeError: list indices must be integers or slices, not str | How to do associative arrays in Python?

I am getting the following error in Python 3.8:
results['article'] = row[0]
TypeError: list indices must be integers or slices, not str
My query:
curb = conn.cursor(buffered=True)
curb.execute("""
SELECT
article,
url
FROM
table
WHERE
id = %s
-- %s
LIMIT 2
""", (
test_id,
test_id
)
)
results = curb.fetchall()
for row in results:
results['article'] = row[0]
results['url'] = row[1]
I know there are similar questions on SO, however I could not figure out so far how to build an associative array in python that serves this use case.
My goal is to pass the article along with the yield statement, which is why I am trying to put it into kind of an associative array.
def start_requests(self):
for result in self.results:
if validators.url(result['url']):
yield scrapy.Request(
url=result['url'],
callback=self.parse_item,
meta={'article': result['article']}
)
else:
print("Invalid URL ", format(result['url']))
Is this what you actually want:
curb = conn.cursor(buffered=True)
curb.execute(
# ...
)
# notice the names of variables
fetch_results = curb.fetchall()
results = []
for row in fetch_results:
result = {}
result['article'] = row[0]
result['url'] = row[1]
# collect other information of this row...
results.append(result)
Another problem is that results is an object that is designed to return 0 or more rows of the database. You know (because you have id = xxx) that only one row will be returned. It looks like you want something like:
for row in results:
answer = dict(article=row[0], url=row[1])
break
You may also want to initialize answer to None in case that no rows are returned.
Based on your comments below, it sounds like you want:
answer = {}
for row in result:
article = row[0]
url = row[1]
answer[url] = article
which will give you a map from URL to article. If you are comfortable with Python, that can be simplified to one line using dictionary comprehension:
answer = {row[1]: row[0] for row in result}

How to get id(address) of each value in list in python like pointer C?

First of all, I'm not good at English, sorry.
I'm trying to get id of list in python, to make each variable get filtered value by locale function.
Please check out the code below.
dayLow ="123124"
dayHigh = "200000"
volume = "21512542"
marketCap = "235136346137"
toLocale = [dayLow, dayHigh, volume, marketCap]
afterLocale = list()
def locale(inform_data):
inform_data = f"{inform_data:,}"
return inform_data
for item in toLocale:
item = locale(int(item))
afterLocale.append(item)
i = 0
while(i < afterLocale):
id(toLocale[i]) = afterLocale[i]
i += 1
and it's not working, and spit error out like that.
File "c:\******\test.py", line 19
id(toLocale[i]) = afterLocale[i]
^
SyntaxError: cannot assign to function call
So the question is
How can each variable in toLocale(dayLow, dayHigh, ...) gets the value filtered by function locale()?
You can't assign to a variable by using it's id() - that's not what id() is for.
If you want to dynamically assign variables to values, you can use exec to do so.
But I WOULD HIGHLY RECOMMEND NOT DOING SO.
Just type out the extra code required. It'll save you a lot of headache in the long run
dayLow ="123124"
dayHigh = "200000"
volume = "21512542"
marketCap = "235136346137"
toLocale = {'dayLow': dayLow, 'dayHigh': dayHigh, 'volume': volume, 'marketCap': marketCap}
def locale(inform_data):
inform_data = f"{inform_data:,}"
return inform_data
for var_name, var_value in toLocale.items():
exec(f'{var_name} = "{locale(int(var_value))}"')
print(dayLow, dayHigh, volume, marketCap)
Output:
123,124 200,000 21,512,542 235,136,346,137
I'm not sure if this is what exactly you want, but if you are trying to translate the values, using a dictionary would be maybe better for your usecase:
items = {
"dayLow": 123124,
"dayHigh" 200000,
"volume": 21512542,
"marketCap": 235136346137,
}
# now you can use `locale` for the keys:
for name, value in items.values():
# `name` will have a value of "dayLow", "dayHigh" etc...
print(locale(name), value)

Finding average value of list elements, if a condition is met using Python?

I have a list that has the following format:
mylist = ["Joe, 100%", "Joe, 80%", "Joe, 90%", "Sally, 95%", "Sally, 80%", "Jimmy, 90%", ...]
What I am trying to do is, first count the number of times each name appears. If a name appears 2 or more times, append that name along with the average percent. So, I'm trying to get to the following output:
newlist = ["Joe, 90%", "Sally, 87.5%"]
To try this, I did mylist.split(", ") to get the names only, and used Counter() to find how many times the name appears. Then, I used a simple if >= 2 statement to append the name to newlist if the name appears 2 or more times.
However, despite trying many different things, but I wasn't able to figure out how to get the percentages back with the name in the final list. I also am unsure how to word my question on Google, so I wasn't able to find any help. Does anyone know how to do this? If this question is a duplicate, please let me know (and provide a link so I can learn), and I can delete this question. Thanks!
You can try this:
from collections import defaultdict
counts = defaultdict(int)
percents = defaultdict(int)
for item in mylist:
name, percent = item.split(',')
percent = int(percent.lstrip().rstrip('%'))
percents[name]+=percent
counts[name]+=1
result = []
for k,v in counts.items():
if v > 1:
result.append(f"{k}, {percents[k]/v}%")
print(result)
Output
['Joe, 90.0%', 'Sally, 87.5%']
I would recommend you create a dictionary of the scores, where the key would be the name and the value would be a list of their scores. This snippet shows how you can achieve that:
mydict = {}
for item in mylist:
name, score = item.split(", ") # splits each item into a score and a name
score = float(score.replace("%", "")) # converts string score to a float
if mydict[name]: # checks if the name already exists in the dictionary
mydict[name].append(score)
else:
mydict[name] = [score]
This would would leave you with a dictionary of scores that is organized by their name. Now all you would have to do is average the scores in the dictionary:
newlist = []
for name in mydict:
if len(mydict[name]) >= 2:
average = str(sum(mydict[name]))/len(mydict[name])) + "%"
straverage = name + ", " + average
newlist.append(straverage)

Rallydev API pyral: Is there way to get all defects by Formatted ID in one query?

I have a list of defects with different IDs. I need to go thru the list and gather fixed / verified defects to separate list.
Could you please advise if there is a way to make in one query (e.g. send a tuple in query) instead of each time send a new get request?
currently it looks like:
items = ("DE111", "DE123", "DE345")
defects = []
for item in items:
criteria = 'FormattedID = "%s"' % item
response = rally.get('Defect', fetch="Name,State", query=criteria)
for defect in response:
defects.append(defect)
Thank you in advance!
Using a little Python 3 you can string together an 'or' conditional on the Formatted ID... If you don't have Python 3 I'm sure the same thing can be accomplished in 2. The important part is the ultimate query string which is : (((FormattedID = DE111) OR (FormattedID = DE112)) OR (FormattedID = DE123))
see an example on repl.it
from functools import reduce
items = ("DE111", "DE112")
def byFormattedId(value):
return "(FormattedID = \"%s\")" % value
def ors(statement, value):
return "(%s OR %s)" % (statement, value)
x = list(map(byFormattedId, items))
y = reduce(ors, x)

Categories

Resources