Devdit
 

Dictionary Python ตัวอย่างการสร้าง และเรียกใช้งาน

0.9K

Dictionary Python ตัวอย่างการสร้าง และเรียกใช้งาน บทความนี้สอนการสร้างตัวแปรชนิด Dictionary ทั้งแบบเก็บ 1 ข้อมูล (Single Value) และแบบเก็บหลายข้อมูล (Multi Value) สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่างที่ 1 Dictionary Python แบบเก็บ 1 ข้อมูล (Single Value)

d = {
  "title": "Python Programming",
  "author": "Mr.A",
  "price": 250
}

print( d )
print( d['title'], "/", d['author'], "/", d['price'] )

ผลลัพธ์

{'title': 'Python Programming', 'author': 'Mr.A', 'price': 250}
Python Programming / Mr.A / 250

คำอธิบาย

Dictionary Python ตัวอย่างนี้ เป็นแบบเก็บ 1 ข้อมูล value คู่กับ 1 key หมายความว่าในแต่ละ key เช่น title จะมี value เพียงอันเดียว คือ Python Programming

 

ตัวอย่างที่ 2 Dictionary Python แบบเก็บหลายข้อมูล (Multi Value)

d = {
  "title": ["Python Programming", "PHP Language"],
  "author": ["Mr.A", "Mr.B"],
  "price": [250, 250]
}

print( d )
print( d['title'][0], "/", d['author'][0], "/", d['price'][0] )
print( d['title'][1], "/", d['author'][1], "/", d['price'][1] )

ผลลัพธ์

{'title': ['Python Programming', 'PHP Language'], 'author': ['Mr.A', 'Mr.B'], 'price': [250, 250]}
Python Programming / Mr.A / 250
PHP Language / Mr.B / 250

คำอธิบาย

Dictionary Python ตัวอย่างนี้ แบบเก็บหลายข้อมูล หมายความว่าในแต่ละ key เช่น title จะมี value หลายอัน จากตัวอย่างมีทั้งหมด 2 value คือ Python Programming และ PHP Language

แก้ไข 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ