Get several values in a query

2

I have this code:

cursor.execute('SELECT nom FROM productes WHERE listacompra = 1')
  rows = cursor.fetchall()
  for row in rows:
  print(row[0])

In the SQL database, I have two rows with something like this:

id 1, nom Custard, list purchase 1

id 2, nom Chocolate, listacompra 1

What I want to achieve is exactly what the previous code shows me but simply stored in one variable (like dictionaries) or in several. Taking into account that we do not know how many rows there are with shopping list = 1.

Thank you very much

    
asked by Nico 06.09.2017 в 19:42
source

2 answers

1

What you get from a cursor.fetchall() is a list of tuples, so you have indicated in the comments, something like: [(u'Natillas',), (u'Chocolate',)] . That is, tuples of a single element, logically, because the select only lists a single column. To transform this output into a "flat" list, you can use list comprehension in the following way:

rows = [(u'Natillas',), (u'Chocolate',)]
nombres = [row[0] for row in rows]
print(nombres)

> ['Natillas', 'Chocolate']

Basically what we are doing is extract the first element of each tuple row[0] and stay alone with it. An important fact, doing this only makes sense when you simply want to stay or have a single column, if you had more the list structure of tuples would be more appropriate.

    
answered by 06.09.2017 / 20:06
source
0

Given the code you publish, you do not have to do anything special, in fact, you already have the results stored in the variable rows , which you then go through to print each row.

If you do not want to print, simply stop going through the list and do something else with it.

cursor.execute('SELECT nom FROM productes WHERE listacompra = 1')
  rows = cursor.fetchall()
  #listo, los resultados están en la variable rows.
    
answered by 06.09.2017 в 19:52