2

I'm working with kinterbasdb to select and update some data from databases of 1998 (yes, unfortunatly :(). And the API of kinterbasdb return the values from queries in tuples, for example:

connection = connect(dsn="database.gdb", user="MYUSER", password="MYPASSWORD")
cursor = connection.cursor()
cursor.execute("SELECT * FROM TABLE_X")
result = cursor.fetchone() # tuple => (value1, value2, value3, value4, value5)

And i would like to map this tuple to a named tuple. Is it possible?

I'm using Python 2.7.13 (i was able to update the kinterbasdb module to make it work... at least)

2 Answers2

4

Just pass your tuple to the namedtuple constructor as expanded args using *.

In [1]: from collections import namedtuple

In [2]: Response = namedtuple('Response', ['thing1', 'thing2', 'thing3', 'thing4'])

In [3]: mytuple = (1, 2, 3, 4)

In [4]: Response(*mytuple)
Out[4]: DBResponse(thing1=1, thing2=2, thing3=3, thing4=4)
a p
  • 3,098
  • 2
  • 24
  • 46
  • While it's not strictly an error, I think it would be much better to use the same variable name for your `namedtuple` type that you pass to it as its name. That is, either change `Response` to `DBResponse`, or visa versa. – Blckknght Feb 14 '17 at 00:43
0

Example:

from collections import namedtuple
t=("value1", "value2", "value3", "value4", "value5")
Data=namedtuple("Data",["v1","v2","v3","v4","v5"])
nt=Data(*t)
>>> nt
Data(v1='value1', v2='value2', v3='value3', v4='value4', v5='value5')

Or use the _make method:

>>> Data._make(t)
Data(v1='value1', v2='value2', v3='value3', v4='value4', v5='value5')
dawg
  • 98,345
  • 23
  • 131
  • 206