Home / Dictionary

Dictionary

You are not logged in.

If you are a current student, please Log In for full access to this page.

Table of Contents

1) Dictionary


1.1) dictionary คืออะไร

  • dictionary เป็น collection ที่มีการเรียงลำดับ (ordered) โดยเก็บข้อมูลเป็น
  • set ของคู่ key: value (item)
  • key จะต้องไม่เหมือนกัน (unique) ภายใน dict โดยเป็นข้อมูลประเภท immutable
  • แต่ละ key จะเก็บหนึ่ง value

1.2) วิธีการใช้งาน

d1 = {}
d2 = dict()
print(d1)
print(d2)
{}
{}
  • การสร้าง
std = {'001':'John', '005': 'Mary', '003': 'Mary'}
print(std)
print(std['001'])
print(len(std))
{'001': 'John', '005': 'Mary', '003': 'Mary'}
John
3
  • ใช้ for ในการวนค่า keys ใน dict
std = {'001':'John', '005': 'Mary', '003': 'Mary'}
for k in std:
  print(k, std[k])
001 John
005 Mary
003 Mary

  • จากโค้ดด้านล่าง จงเขียนโค้ดเพิ่มเติมเพื่อ
    1. แสดงจำนวนวิชาทั้งหมดใน dictionary ชื่อ score
    2. แสดงชื่อวิชาและคะแนนที่ได้เกรด 4 ออกทางจอภาพ (วิชาที่ได้เกรด 4 คือ วิชาที่ได้คะแนนไม่ต่ำกว่า 80 คะแนน)
  • ผลลัพธ์ที่ควรได้คือ
5
Math 80
Computer 82

  • การวน keys ด้วย for ธรรมดาจะไม่เรียงตามอะไรเลย หากต้องการเรียงให้ใช้ sorted ประกอบ
prov = {'Bangkok': 3630.9,
        'NakhonPathom': 420.4}
for k in sorted(prov):
  print(k, prov[k])
Bangkok 3630.9
NakhonPathom 420.4
prov = {'Krabi': 4709, 'Bangkok': 3630.9, 'NakhonPathom': 420.4}
print(sorted(prov))
for k in sorted(prov):
  print(k, prov[k])
for k in ['Bangkok','Krabi', 'NakhonPathom']:
  print(k, prov[k])
['Bangkok', 'Krabi', 'NakhonPathom']
Bangkok 3630.9
Krabi 4709
NakhonPathom 420.4
Bangkok 3630.9
Krabi 4709
NakhonPathom 420.4

2) Exercise

2.1) Exercise 1

จากโค้ดตั้งต้นด้านล่าง ฟังก์ชัน province_area เป็นฟังก์ชันที่ส่งค่ากลับ (return) เป็น list ของ tuple (ชื่อจังหวัด, พื้นที่)

โดยในฟังก์ชัน province_area จะมี dictionary ชื่อ prov ที่เก็บข้อมูลพื้นที่ (หน่วยเป็นตารางกิโลเมตร) ของจังหวัดในประเทศไทย 77 จังหวัด (ข้อมูลปี 2017) โดยมี

  • key คือ จังหวัด และ
  • value คือ พื้นที่ ให้แล้ว

งานของคุณ

  1. ทดลองรันโค้ดตั้งต้น แล้วสังเกตผลลัพธ์และศึกษาโค้ดตั้งต้นดังกล่าว หลังจากนั้น ...
  2. ปรับปรุงฟังก์ชัน province_area เพิ่มเติม โดย
    • ให้มี argument 1 ตัว คือ n สำหรับรับค่าจำนวนเต็ม
    • เป็นฟังก์ชันที่ส่งค่ากลับเป็นข้อมูลของจังหวัดที่มีพื้นที่มากกว่า n ตารางกิโลเมตร
    • รูปแบบการส่งค่ากลับคล้ายเดิม คือ ส่งค่ากลับเป็น list ของ tuple (ชื่อจังหวัด, พื้นที่) โดยให้เรียงลำดับชื่อจังหวัดตามตัวอักษร A ถึง Z ด้วย

ตัวอย่างการเรียกใช้ฟังก์ชัน province_area เมื่อปรับปรุงโค้ดแล้ว

province_area(20000) == [('Chiang Mai', 20107), ('Nakhon Ratchasima', 20494)]


3) การใช้งาน Dictionary

  • การ update ค่า
prov = {'Bangkok': 3630.9,
        'NakhonPathom': 420.4}
prov['Bangkok'] = 3650
for k in sorted(prov):
  print(k, prov[k])
Bangkok 3650
NakhonPathom 420.4
prov = {'Bangkok': 3630.9,
        'NakhonPathom': 420.4}
prov['BANGKOK'] = 3650
for k in sorted(prov):
  print(k, prov[k])
BANGKOK 3650
Bangkok 3630.9
NakhonPathom 420.4
prov = {'Bangkok': 3630.9,
        'NakhonPathom': 420.4}
prov['Nan'] = 41.8
for k in sorted(prov):
  print(k, prov[k])
Bangkok 3630.9
NakhonPathom 420.4
Nan 41.8
  • ใช้ update() ในการแก้ไขค่าหลายค่าพร้อมกัน
prov = {'Bangkok': 3630.9,
        'NakhonPathom': 420.4}
prov.update({'Nan': 41.8})
for k in sorted(prov):
  print(k, prov[k])
Bangkok 3630.9
NakhonPathom 420.4
Nan 41.8
prov = {'Bangkok': 3630.9,
        'NakhonPathom': 420.4}
prov.update({'Tak': 33.0, 'Nan': 41.8})
for k in sorted(prov):
  print(k, prov[k])
Bangkok 3630.9
NakhonPathom 420.4
Nan 41.8
Tak 33.0
prov = {'Bangkok': 3630.9,
        'NakhonPathom': 420.4}
p2 = {'Tak': 33.0, 'Nan': 41.8, 'Bangkok': 4000.5}
prov.update(p2)
for k in sorted(prov):
  print(k, prov[k])
Bangkok 4000.5
NakhonPathom 420.4
Nan 41.8
Tak 33.0

3.1) สรุป Dictionary

  • ใช้เก็บข้อมูลแบบคู่อันดับ (key,value)
  • ในแต่ละ dictionary ไม่มี key ที่ซ้ำกัน และข้อมูลที่เก็บใน key ต้องเป็น immutable (เช่น int, float,str, tuple, bool)
  • value ซ้ำกันได้ และประเภทข้อมูลที่จัดเก็บใน value จะเป็นอะไรก็ได้

3.2) Dictionaries : as a collection of counters

  • สามารถใช้ in ในการค้นหา key ใน dictionary (สามารถ not in ในการค้นหาว่าไม่มีอยู่ ก็ได้เช่นกัน)
  • จากตัวอย่างด้านล่าง
    1. กำหนดให้ d เป็น dictionary ว่าง
    2. วนซ้ำเพื่ออ่านข้อมูลย่อยใน txt (ในที่นี้คือตัวอักษร)ทีละตัว
    3. ใช้ in ในการค้นหาว่ามี ch เป็น key อยู่ใน dictionary d หรือไม่
    4. ถ้ามี ch เป็น key อยู่ใน d ก็จะทำการเพิ่มค่า value ขึ้นทีละหนึ่ง (นับเพิ่มทีละหนึ่ง)
    5. ถ้ายังไม่มี ch เป็น key อยู่ใน d ก็จะเพิ่มทั้ง key และ value เข้าไปใน d โดยกำหนดให้ value เริ่มต้นเป็น 1
    6. เมื่อออกจาก loop จึงแสดงข้อมูลใน d
txt = 'CCBDDDABBBACDBBDDCCAAABCDAAA'
d = {}
for ch in txt:
  if ch in d: 
    d[ch] += 1  #เหมือนกับคำสั่ง d[ch] = d[ch]+1
  else:
    d[ch] = 1
print(d)
{'C': 6, 'B': 7, 'D': 7, 'A': 8}

3.3) Dictionaries methods

  • keys() : Returns a new object of the dictionary's keys.
  • values() : Returns a new object of the dictionary's values.
  • items() : Return a new object of the dictionary's items in (key, value) format.
d = {'C': 6, 'B': 7, 'D': 7, 'A': 8}
print(d.keys())
print(d.values())
print(d.items())
dict_keys(['C', 'B', 'D', 'A'])
dict_values([6, 7, 7, 8])
dict_items([('C', 6), ('B', 7), ('D', 7), ('A', 8)])
d = {'C': 6, 'B': 7, 'D': 7, 'A': 8}
val = d.values()
print(sum(val)/len(val))
print(max(val))
7.0
8
d = {'C': 6, 'B': 7, 'D': 7, 'A': 8}
val = list(d.values())
print(val[0])
print(val)
for v in d.values():
  print(v)
6
[6, 7, 7, 8]
6
7
7
8
d = {'C': 6, 'B': 7, 'D': 7, 'A': 8}
key = list(d.keys())
val = list(d.values())
print(key)
print(val)
['C', 'B', 'D', 'A']
[6, 7, 7, 8]
  • ใช้ dict() และ zip() ในการแปลง list ความยาวเท่ากันเป็นคู่ key:value สำหรับ dictionary
a = ['001', '012', '008']
b = [9.5, 8.7, 10]
score = dict(zip(a, b))
print(score)
{'001': 9.5, '012': 8.7, '008': 10}

4) Exercise

4.1) Exercise 2

สมมติให้ bg คือ ลิสต์ที่เก็บข้อมูลหมู่เลือดของคน เช่น

bg = ['A', 'B', 'AB', 'B', 'O', 'AB', 'O', 'B', 'O', 'A', 'AB', 'B', 'B', 'AB', 'O', 'O', 'O', 'A', 'A', 'B', 'B', 'O', 'O', 'O', 'O']

กำหนดให้ blood เป็น dictionary ที่เก็บจำนวนของคนแต่ละหมู่เลือด มี

  • key คือ หมู่เลือด และ
  • value คือ จำนวนคน โดยกำหนดค่าเริ่มต้นให้ blood เป็น dictionary ว่าง

จงเขียนฟังก์ชัน blood_count เพื่อแปลงจาก list ของหมู่เลือดเป็น dictionary ที่เก็บ key เป็นหมู่เลือด และ value เป็นจำนวนคนของหมู่เลือดนั้น

ตัวอย่างการเรียกใช้ฟังก์ชัน blood_count

bg = ['A', 'B', 'A', 'AB', 'O']  
print(blood_count(bg))  

ซึ่งผลลัพธ์ที่ควรได้คือ

{'A': 2, 'B': 1, 'AB': 1, 'O': 1}


4.2) Exercise 3

พิจารณาสตริง article ซึ่งเป็นสตริงเก็บบทความภาษาอังกฤษ ดังนี้

article = 'A liquid is traditionally defined as a material that adapts its shape to fit a container. Yet under certain conditions, cats seem to fit this definition. This somewhat paradoxical observation emerged on the web a few years ago and joined the long list of internet memes involving our feline friends. When I first saw this question it made me laugh, and then think. I decided to reformulate it to illustrate some problems at the heart of rheology, the study of the deformations and flows of matter. My study on the rheology of cats won the 2017 Ig Nobel Prize in Physics. The prizes are awarded every year by Improbable Research, an organization devoted to science and humor. The goal is to highlight scientific studies that first make people laugh, then think. A ceremony is held every year at Harvard University.'

จงเขียนฟังก์ชัน article_dict เพื่อ

  • รับสตริง article และ
  • return dictionary ที่เก็บ
    • key เป็นอักขระ a-z (นับพิมพ์เล็กและพิมพ์ใหญ่รวมกันโดยให้ key เป็นพิมพ์เล็ก) และ
    • value เป็นจำนวนครั้งที่อักขระดังกล่าวปรากฏใน article

ตัวอย่างการเรียกใช้ฟังก์ชัน article_dict

ex = 'A Solid or a Liquid?'  
print(article_dict(ex))   

ซึ่งผลลัพธ์ที่ควรได้คือ

{'a': 2, 's': 1, 'o': 2, 'l': 2, 'i': 3, 'd': 2, 'r': 1, 'q': 1, 'u': 1}

🌐 ที่มาของตัวอย่าง article :
https://theconversation.com/answering-the-question-that-won-me-the-ig-nobel-prize-are-cats-liquid-86589

Hint

ลองรันโค้ดด้านล่างนี้ ซึ่งจะตรวจสอบตัวอักษรใน st ทีละตัวว่าเป็นตัวอักษร a-z หรือไม่ โดยจะแสดง y หากเป็นตัวอักษร a-z

st = 'Hi! world:)'
for ch in st:
    if ch.isalpha():
        print('y')
    else:
        print('n')