2

I am connecting to snowfalke database and fetch only 1 record. This record will have 21 columns. After i read them in python using connection, they return a tuple object.

I want to access the elements of tuple object with a name.

Preferrably i want to access these tuple elemts with the same name as column name from database.

In PL/SQL, we have something called as record type. And the elements in record can be accessed with a name

How do i do this in python?

Pseudocode ex:

tup_obj = connection.execute('select name, age, height, weight from table')

I want to access the tuple object like with names like this,

tup_obj.name == 'Harish'?

The above is only an example of the requiment. The below is the simulated data with same structure for my use case:

print(type(tup_obj))
print(tup_obj)

<class 'tuple'>
(101010, 5, 1, 200, 'text', 'text', 'text', 'text', 18075, 'text', 'text', 'text', 37, 2, 57, 'Y', 'S', 'S', 'text', 123, 'text')

1 Answer 1

2

Use a dictionary data structure to store and access like tup_obj.name

columns = ['name', 'age', 'height', 'weight']
data = [('a', 20, 170, 80)] # This will be your select query results
out = [dict(zip(columns, x)) for x in data]

Output

[{'name': 'a', 'age': 20, 'height': 170, 'weight': 80}]

Access using

out[0]['name'] # This will give string 'a'

EDIT:

For tuple, use directly

dict(zip(columns, data))
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks. I tried this in actual data.. getting error : zip argument #2 must support iteration
You should post some data @HarikrishnanBalachandran in your question
I am sorry I can't do that. But thanks for the idea. I will try to fix the error.
@HarikrishnanBalachandran If you want people helping you in SO, you need to have a proper minimal example. Don't post the actual data. Post some dummy data with same structure.
have you tried using a namedtuple from the module collections
|

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.