0

I'm trying to create a loop with Python and imported SQL data. Right now I can run a loop for any hardcoded value, however I'm getting an error when adding in the variable i. Below is my current code:

start = %sql SELECT * FROM streets
end = %sql SELECT * FROM streets
#path.keys
# [u'id', u'value1', u'value2', u'value3', u'value4']
for i in start:
 print start[3][4]

This will print out a repeating value of what is in value4 on row 3. What I'm trying to do is rewrite the the loop so that it will render the value of row i. For example

for i in start:
 print start[i][4]

However this gives me an error

---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-215-bc2196cf4539> in <module>()
 5 
 6 for i in start:
----> 7 print start[i][4]
 8 
/Users/xxxxx/homebrew/lib/python2.7/site-packages/sql/run.pyc in __getitem__(self, key)
 136 result = [row for row in self if row[0] == key]
 137 if not result:
--> 138 raise KeyError(key)
 139 if len(result) > 1:
 140 raise KeyError('%d results for "%s"' % (len(result), key))

Any thoughts on how to rewrite this to pull in i and render the value row by row?

Thanks in advance!

asked Oct 6, 2015 at 0:59

1 Answer 1

1

If Start is a list, this would work:

for i in range(len(start)):
 print start[i]

To find out what start is and how to handle it, you can do type(start)). If it's some sort of SQL cursor, it wouldn't have a length property, but then you should be able to do:

for i in start:
 print i
answered Oct 6, 2015 at 1:06
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.