1

I'm storing FB post ids in a sqlite table. Now I want to query other data in the FB graph using the post_id. The hack below works but it feels pretty hokey...

cur.execute("SELECT post_id FROM fbposts") 
data_all = cur.fetchall()
for x in data_all:
    y = "%s" % x

the value of y is now something like 96085205666_10153983162390667 and can be used to construct a new FB api call but there must be a more pythonic way

2
  • I may be missing something- x doesn't act like a string; type(x) returns <type 'tuple'> type(x[0]) returns <type 'buffer'> Commented Dec 20, 2016 at 7:17
  • @sisanared no it returns a tuple. see my answer. Commented Dec 20, 2016 at 7:18

2 Answers 2

4

With your request, data_all is an iterable on tuples of 1 element

`y = "%s" % x` properly converts a 1-element tuple to a string, but you're right, it's not the best way.

fetchall(): Fetches all (remaining) rows of a query result, returning a list. Note that the cursor’s arraysize attribute can affect the performance of this operation. An empty list is returned when no rows are available.

To take this element and create a list with the strings, do:

[x for (x,) in data_all]

this unpacks x inside the tuple and creates a list of strings (equivalent to [x[0] for x in data_all])

Sign up to request clarification or add additional context in comments.

2 Comments

That's interesting, I've never seen the x for (x,) pattern before. Nice to know now.
yeah that was the occasion to expose it :)
2

What about using the following pattern:

cur.execute("SELECT post_id FROM fbposts") 
data_all = [item[0] for item in cur.fetchall()]

Now your data_all will be the list of strings that you want. And if you want to make a call for each post_id, you can now do:

for post_id in data_all:
    fb.call(post_id)

1 Comment

I made a small change to get a string... data_all = [str(item[0]) for item in cur.fetchall()]

Your Answer

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.