I made a SQLite query in Python like that:
SharesOwned = db.execute("SELECT SUM(Shares) FROM transactionTable WHERE Share='FB'")
print(SharesOwned)
if sharesOwned < sharesToSell:
return errorMessage("You don't own that many shares of FB")
It prints:
[{'SUM(Shares)':10}]
Then it gives me this error:
TypeError: "List indices must be integers or slices not str"
How can I extract the number as an integer?
It looks like SharesOwned is a list of dictionaries. To return the number of shares you need to do the following in this particular case:
SharesOwned[0]['SUM(Shares)']
SharesOwned[0] accesses the first element of the list, in this case a dictionary {'SUM(Shares)':10}. Now you just need to lookup the value by key - 'SUM(Shares)' in this case.
Additionally, it looks like you have a typo in sharesOwned, s should be capitalized.
Try below changes :
Update your query:
SELECT SUM(Shares) AS total FROM transactionTable WHERE Share='FB'
Then access SharedOwned:
if SharedOwned[0]['total']<sharesToSell:
I've got a list of dictionaries with a xpath query from a HTML file.
It is something like this:
[{"not-interested-in":"", "url": url_string1},
{"not-interested-in":"", "url": url_string2}, and so on...]
Now I try to obtain a new list with all the values of the "url" key from all the dictionaries:
[url_string1, url_string2, ...]
I tried list comprehension as it was the most recommended method, and I did this(data is the list of dictionaries):
data = tree.xpath('(//li[#data-bns="API"]/#data)[position() <= 5]')
imageURLs = [di['url'] for di in data]
When running, I got an error message something like this:
TypeError: string indices must be integers, not str
Can anybody help me, please?
In imageURLs = [di['url'] for di in data] you're trying to index into an object (di, which is a string), using another string ('url') as your index. Strings don't support string indexing!
(E.g. 'Hello!'['a'] will return the same error.)
I have a dictionary within a dictionary like below:
My code looks for todays date and if it exists in dict it should print “found a match at” + dict(name)
today = datetime.datetime.now()
if today in dict[name]:
print "Found a bday for " + str(dict[name])
#here i need a variable that will hold the email from that name so I can use to somewhere else
If I excuse print dict
It looks like this:
{'name1': set(['01-25', 'name1#company.com']), 'name2': set(['name2#company.com', '11-29']), 'name3': set(['08-15', 'name3#company.com']), 'name4': set(['01-24', 'name4#company.com'])}
My questions is how do I access the email. I understood the hard way that the values in my dictionary are currently a ‘set’ that I can’t access by indexing. Once I do print dict[name][1] then I get the error TypeError:
'set' object does not support indexing
Sets are unordered data structures, so you cannot access them with the index.
Even if you typecast them to a list, and then use a index,i.e. list(dict[name])[1] it is not guaranteed to return correct element, as the order of the list is not defined.
Your way to pick out matching element can be to iterate the set, and select the element which matches conditions like type and any possible regex, but that is also prone to error, unless your sets have few elements of different types.
You are using a set when you create the dict, where you should be using a list or a tuple.
dict.setdefault(name, [emails,bdays])
You could use something like this:
date = today.strftime('%m-%d')
for names in var.keys():
if date in var[names]:
for x in var[names]:
if x != date:
email = x
print "Found a bday for " + email
But there are better options to store this information.
I'm trying to manipulate a list of items in python but im getting the error "AttributeError: 'list' object has no attribute 'split'"
I understand that list does not understand .split but i don't know what else to do. Below is a copy paste of the relevant part of my code.
tourl = 'http://data.bitcoinity.org/chart_data'
tovalues = {'timespan':'24h','resolution':'hour','currency':'USD','exchange':'all','mining_pool':'all','compare':'no','data_type':'price_volume','chart_type':'line_bar','smoothing':'linear','chart_types':'ccacdfcdaa'}
todata = urllib.urlencode(tovalues)
toreq = urllib2.Request(tourl, todata)
tores = urllib2.urlopen(toreq)
tores2 = tores.read()
tos = json.loads(tores2)
tola = tos["data"]
for item in tola:
ting = item.get("values")
ting.split(',')[2] <-----ERROR
print(ting)
To understand what i'm trying to do you will also need to see the json data. Ting outputs this:
[
[1379955600000L, 123.107310846774], [1379959200000L, 124.092526428571],
[1379962800000L, 125.539504822835], [1379966400000L, 126.27024617931],
[1379970000000L, 126.723474983766], [1379973600000L, 126.242406356837],
[1379977200000L, 124.788410570987], [1379980800000L, 126.810084904632],
[1379984400000L, 128.270580796748], [1379988000000L, 127.892411269036],
[1379991600000L, 126.140579640523], [1379995200000L, 126.513705084746],
[1379998800000L, 128.695124951923], [1380002400000L, 128.709738051044],
[1380006000000L, 125.987767097378], [1380009600000L, 124.323433535528],
[1380013200000L, 123.359378559603], [1380016800000L, 125.963250678733],
[1380020400000L, 125.074618194444], [1380024000000L, 124.656345088853],
[1380027600000L, 122.411303435449], [1380031200000L, 124.145747100372],
[1380034800000L, 124.359452274881], [1380038400000L, 122.815357211394],
[1380042000000L, 123.057706915888]
]
[
[1379955600000L, 536.4739135], [1379959200000L, 1235.42506637],
[1379962800000L, 763.16329656], [1379966400000L, 804.04579319],
[1379970000000L, 634.84689741], [1379973600000L, 753.52716718],
[1379977200000L, 506.90632968], [1379980800000L, 494.473732950001],
[1379984400000L, 437.02095093], [1379988000000L, 176.25405034],
[1379991600000L, 319.80432715], [1379995200000L, 206.87212398],
[1379998800000L, 638.47226435], [1380002400000L, 438.18036666],
[1380006000000L, 512.68490443], [1380009600000L, 904.603705539997],
[1380013200000L, 491.408088450001], [1380016800000L, 670.275397960001],
[1380020400000L, 767.166941339999], [1380024000000L, 899.976089609997],
[1380027600000L, 1243.64963909], [1380031200000L, 1508.82429811],
[1380034800000L, 1190.18854705], [1380038400000L, 546.504592349999],
[1380042000000L, 206.84883264]
]
And ting[0] outputs this:
[1379955600000L, 123.187067936508]
[1379955600000L, 536.794013499999]
What i'm really trying to do is add up the values from ting[0-24] that comes AFTER the second comma. This made me try to do a split but that does not work
You already have a list; the commas are put there by Python to delimit the values only when printing the list.
Just access element 2 directly:
print ting[2]
This prints:
[1379962800000, 125.539504822835]
Each of the entries in item['values'] (so ting) is a list of two float values, so you can address each of those with index 0 and 1:
>>> print ting[2][0]
1379962800000
>>> print ting[2][1]
125.539504822835
To get a list of all the second values, you could use a list comprehension:
second_vals = [t[1] for t in ting]
When you load the data with json.loads, it is already parsed into a real list that you can slice and index as normal. If you want the data starting with the third element, just use ting[2:]. (If you just want the third element by itself, just use ting[2].)
I would like to build up a list using a for loop and am trying to use a slice notation. My desired output would be a list with the structure:
known_result[i] = (record.query_id, (align.title, align.title,align.title....))
However I am having trouble getting the slice operator to work:
knowns = "output.xml"
i=0
for record in NCBIXML.parse(open(knowns)):
known_results[i] = record.query_id
known_results[i][1] = (align.title for align in record.alignment)
i+=1
which results in:
list assignment index out of range.
I am iterating through a series of sequences using BioPython's NCBIXML module but the problem is adding to the list. Does anyone have an idea on how to build up the desired list either by changing the use of the slice or through another method?
thanks zach cp
(crossposted at [Biostar])1
You cannot assign a value to a list at an index that doesn't exist. The way to add an element (at the end of the list, which is the common use case) is to use the .append method of the list.
In your case, the lines
known_results[i] = record.query_id
known_results[i][1] = (align.title for align in record.alignment)
Should probably be changed to
element=(record.query_id, tuple(align.title for align in record.alignment))
known_results.append(element)
Warning: The code above is untested, so might contain bugs. But the idea behind it should work.
Use:
for record in NCBIXML.parse(open(knowns)):
known_results[i] = (record.query_id, None)
known_results[i][1] = (align.title for align in record.alignment)
i+=1
If i get you right you want to assign every record.query_id one or more matching align.title. So i guess your query_ids are unique and those unique ids are related to some titles. If so, i would suggest a dictionary instead of a list.
A dictionary consists of a key (e.g. record.quer_id) and value(s) (e.g. a list of align.title)
catalog = {}
for record in NCBIXML.parse(open(knowns)):
catalog[record.query_id] = [align.title for align in record.alignment]
To access this catalog you could either iterate through:
for query_id in catalog:
print catalog[query_id] # returns the title-list for the actual key
or you could access them directly if you know what your looking for.
query_id = XYZ_Whatever
print catalog[query_id]