ในภาษา Python นั้นตัวแปร tuple กับ ตัวแปร dictionary จะเหมือนกับตัวแปรชนิด array ในภาษา PHP ก่อนอื่นเรามาทำความรู้จักตัวแปร tuple กับ ตัวแปร dictionary กันแบบพอสังเขตกันนะครับ ตัวแปร tuple เป็นตัวแปรที่เก็บข้อมูลแบบลำดับ จะคล้ายๆ กับ ตัวแปรชนิด list จะเก็บค่าของสมาชิกแต่ละตัวไว้ใน เครื่องหมาย (....) ส่วนตัวแปรชนิด dictionary ในภาษา Python จะเรียกว่าเป็น hash table type จะคล้ายกับตัวแปร array ในภาษา PHP และ hash ในภาษา Perl จะมี key และ value คู้กันตลอด ค่าจะอยู่ในเครื่องหมาย {....} แต่ในการนำค่าตัวแปร tuple มาเก็บไว้ในตัวแปร dictionary นั้นต้องมีการใช้ for loop เข้ามาเกี่ยวข้องด้วย โดยจะรูปแบบตัวอย่างดังนี้ครับ
โค้ด: เลือกทั้งหมด
import psycopg2 as p
try:
con=p.connect(host='localhost', database='test', user='postgres')
cur=con.cursor()
sql="""SELECT * FROM "test_python";"""
sql=sql.encode('utf-8')
cur.execute(sql)
resufts=cur.fetchall()
print(resufts)
except p.DatabaseError:
print('Error : %s'%p.DatabaseError)
โค้ด: เลือกทั้งหมด
import psycopg2 as p
try:
con=p.connect(host='localhost', database='test', user='postgres')
cur=con.cursor()
sql="""SELECT * FROM "test_python";"""
sql=sql.encode('utf-8')
cur.execute(sql)
resufts=cur.fetchall()
for tp_var in resufts:
print(tp_var)
except p.DatabaseError:
print('Error : %s'%p.DatabaseError)
โค้ด: เลือกทั้งหมด
import psycopg2 as p
try:
con=p.connect(host='localhost', database='test', user='postgres')
cur=con.cursor()
sql="""SELECT * FROM "test_python";"""
sql=sql.encode('utf-8')
cur.execute(sql)
resufts=cur.fetchall()
dic_var={}
for tp_var in resufts:
dic_var[tp_var[1]]=tp_var[2]
print(dic_var)
except p.DatabaseError:
print('Error : %s'%p.DatabaseError)
https://www.stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops
http://www.marcuscode.com/lang/python/dictionary
https://www.sites.google.com/site/pythonclassroom/python-tutorial/python-dictionary-variable