Dictionary comprehension
Dictionary comprehension มีรูปแบบคล้ายกับ list comprehension มาก ต่างกันที่ผลลัพธ์ที่ได้เป็น dictionary แทนที่จะเป็น list จำไว้ว่าแต่ละ element ใน dictionary ประกอบด้วย 2 ส่วน ได้แก่ key และ value โดยคั่นด้วยเครื่องหมายโคลอน
ตัวอย่าง dictionary comprehension ด้านล่างนี้จะยกกำลังสองค่าทุกตัวใน list:
x = [['a', 1], ['b', 2], ['c', 3], ['d', 4]]
print({key:(value**2) for (key, value) in x})
{'a': 1, 'b': 4, 'c': 9, 'd': 16}
หมายเหตุ:
- เมื่อ print dictionary ลำดับการแทรก element จะถูกเก็บรักษาไว้
- Dictionary comprehension จะถูกครอบด้วย
{ }
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python สำหรับผู้ใช้ R
คำแนะนำการฝึกหัด
- ตรวจสอบเนื้อหาของ 2D list
twitter_followersใน shell - เขียน dict comprehension โดยให้ key เป็น element แรกของ sub-list และ value เป็น element ที่สอง แล้วเก็บไว้ในตัวแปร
tf_dict - Print
tf_dict
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Write a dict comprehension
tf_dict = {____:____ for ____,____ in ____}
# Print tf_dict
print(____)