dict ใน python เป็นโครงสร้างข้อมูลชนิดนึง ที่ใช้เก็บ key -> value ได้ เวลาเขียนโปรแกรมกับ dict เราก็มักจะมีท่าที่ต้องเขียนโปรแกรมซ้ำๆ… ผมเพิ่งรู้จักท่าอื่นๆ ที่อยากเอามาแชร์ตามนี้ครับ:
1. defaultdict
เรามักจะต้องเขียนโปรแกรมเช็คว่ามีคีย์ (key) นี้อยู่ใน dict อยู่แล้วรึเปล่า ก่อนที่จะนับค่าเพิ่ม (increment) เช่นโปรแกรมนับความถี่ของตัวอักษรข้างล่างนี้
text = "aaaabbcdeff" freq = {} for c in text: if c not in freq: freq[c] = 0 freq[c] += 1
เราสามารถใช้ defaultdict มาช่วยให้โค้ดดูสวยงามขึ้นได้ตามนี้ (ขอบคุณพี่ @lewcpe ที่แนะนำให้รู้จักฮะ)
from collections import defaultdict text = "aaaabbcdeff" freq = defaultdict(int) for c in text: freq[c] += 1
ตัวอย่างข้างบน เราบอก defaultdict ว่าถ้าคีย์ที่ต้องการยังไม่มี ให้เรียก int() เพื่อกำหนดค่าเริ่มต้น
x = freq['a'] # ปกติจะ KeyError, แต่ถ้าเป็น defaultdict มันจะเรียก freq['a'] = int() # เพื่อกำหนดค่าเริ่มต้นให้
2. .setdefault
เวลาเขียนโปรแกรมอ่านค่าจาก dict เราสามารถใช้เมธอด .get เพื่ออ่านค่าจาก dict ได้โดยไม่ต้องกังวลว่าจะมี คีย์นั้นอยู่รึเปล่า เช่น
options = { 'width': 500 } width = options.get('width', 1000) # 500 height = options.get('height', 300) # 300
ตัวอย่างข้างบน เราสามารถอ่านค่า options[‘width’] ได้สำเร็จ ส่วน height เราได้ค่า default คือ 300 เพราะไม่มีคีย์ height ใน options
สำหรับเมธอด .setdefault นั้นมีพฤติกรรมคล้ายๆ .get แต่มันจะกำหนดค่า default กลับลงไปใน dict ด้วยถ้ายังไม่มีคีย์นั้นใน dict
people_by_blood = { "A": ["Adam", "Eva"], "B": ["John"]} people_by_blood.setdefault("O", []).append("Job") people_by_blood.setdefault("A", []).append("Nin") print people_by_blood {"A": ["Adam", "Eva", "Nin"], "B": ["John"], "O": ["Job"] }
3. คลาส collections.Counter
คลาส Counter เป็นคลาสเฉพาะกิจ ใช้นับ frequency ครับ ดูตัวอย่างเลยดีกว่า
from collections import Counter print Counter("aaaabbcdeff") # Counter({'a': 4, 'b': 2, 'f': 2, 'c': 1, 'e': 1, 'd': 1}) print Counter("aaaabbcdeff").most_common(3) # [('a', 4), ('b', 2), ('f', 2)]
นอกจากใช้นับ frequency ได้ง่ายแล้ว ยังมีเมธอดสะดวกๆ เช่น most_common ให้ใช้ด้วย
ใครมีท่าอื่นๆ ของ dict ใน python อย่าลืมมาแชร์กันนะครับ ^^
โอ้ว เจ๋งเลยพี่