การนำตัวแปร tuple มาเก็บไว้ในตัวแปร dictionary

แชร์ความรู้ภาษา Python ไพทอน การเขียนโปรแกรมภาษาไพทอน

Moderator: mindphp, ผู้ดูแลกระดาน

ภาพประจำตัวสมาชิก
jirawoot
PHP VIP Members
PHP VIP Members
โพสต์: 3129
ลงทะเบียนเมื่อ: 17/06/2019 10:30 am

การนำตัวแปร tuple มาเก็บไว้ในตัวแปร dictionary

โพสต์ที่ยังไม่ได้อ่าน โดย jirawoot »

การนำตัวแปร tuple มาเก็บไว้ในตัวแปร dictionary
ในภาษา 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)
ผลลัพธ์
Selection_034.png
Selection_034.png (7.17 KiB) Viewed 513 times
จากโค้ดตัวอย่างด้านบนถ้าเราแสดงค่าตัวแปร resufts จะเห็นว่าตัวแปรชนิด tuple จะอยู่ในตัวแปร list ต้องทำการวน 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()
    for tp_var in resufts:
        print(tp_var)

except p.DatabaseError:
    print('Error : %s'%p.DatabaseError)
ผลลัพธ์
Selection_035.png
Selection_035.png (11.79 KiB) Viewed 513 times
จากด้านบนจะเห็นได้ว่าเราได้ผลลัพธ์ออกมาเป็นตัวแปรชนิด tuple แล้วจากนั้นก็ทำการนำไปเก็บไว้ในตัวแปรชนิด dictionary ได้แล้ว

โค้ด: เลือกทั้งหมด

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)
ผลลัพธ์
Selection_037.png
Selection_037.png (7.75 KiB) Viewed 513 times
อ้างอิง
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
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 88