2

I am working with a psql database and python, and I need a way to convert each element of a record array into a variable attached to an empty list. I also need to avoid global variables if at all possible. The overall goal is to create a variable with the name of a table, and set the variable equal to a list of column headers. I was able to pull a record array containing the table names from the database, with

tables= db.query2rec("""select table_name from information_schema.tables where table_schema = 'public';""")

where db and query2rec use some psycopg2 stuff to give me

tables= rec.array([('table1',), ('table2',), ('table3',), ('table4',), ('table5',)], 
    dtype=[('table_name', 'O')])

I need to get this in the form of

table1 = []
table2 = []
table3 = []
table4 = []
table5 = []

I can then use a second query to populate each of these with a list of headers from each table. My biggest challenge is getting the elements of the record array as variable names. I have no clue how to do it, although I have spent a few hours looking at everything from pickling and dictionaries to for loops and global variables. Thanks!

Liam Plybon
  • 58
  • 10

1 Answers1

1

A Similar Question is already there: How do you create different variable names while in a loop?

In your case, you have to loop through the array of tuples:

tables= rec.array([('table1',), ('table2',), ('table3',), ('table4',), ('table5',)], 
dtype=[('table_name', 'O')])

I used a 'numpy' array for this, but should work on your array too, this is the code I used:

import numpy as np
tables = np.asarray([('table1',), ('table2',), ('table3',), ('table4',), ('table5',)], 
dtype=[('table_name', 'O')])

for i in range(len(tables)):
    globals()[str(tables[i][0])] = []

Output was:

print(table1)
[]

The tables[i][0] part is to accessing the first element of the tuple, which is the first element of the 'i' position of the array

globals() is to create it a global variable, otherwise it would just be a string, if you access it with something like tables[i][0] and assigning [] to it would just change the original array

prodigal_son
  • 116
  • 8