พจนานุกรมเป็นโครงสร้างข้อมูลที่ใช้กันอย่างแพร่หลายที่สุดในหลาม ประกอบด้วยข้อมูลในรูปแบบของคีย์และค่า ในตัวอย่างนี้ เราจะมาดูวิธีรับไอเท็มจากพจนานุกรมเฉพาะสำหรับชุดคีย์ที่กำหนด
ด้วยความเข้าใจพจนานุกรม
ในแนวทางนี้ เราเพียงแค่วนรอบพจนานุกรมโดยใช้ for loop with inโอเปอเรเตอร์ แต่ร่วมกับตัวดำเนินการ in เรายังกล่าวถึงค่าของคีย์เมื่ออ้างถึงคีย์พจนานุกรมด้วย
ตัวอย่าง
dictA = {'Sun': '2 PM', "Tue": '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'}
# Given dictionary
print("Given dictionary : ",dictA)
res = {key: dictA[key] for key in dictA.keys()
& {'Fri', 'Sun'}}
# Result
print("Dictionary with given keys is : ",res) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given dictionary : {'Sun': '2 PM', 'Tue': '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'}
Dictionary with given keys is : {'Fri': '9 PM', 'Sun': '2 PM'} ด้วย dict()
ในแนวทางนี้ เราเลือกคีย์ที่จำเป็นของพจนานุกรมในขณะที่ส่งคีย์ไปยังฟังก์ชัน dict() สอดคล้องกับการใช้ for วนซ้ำ
ตัวอย่าง
dictA = {'Sun': '2 PM', "Tue": '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'}
# Given dictionary
print("Given dictionary : ",dictA)
res = dict((k, dictA[k]) for k in ['Fri', 'Wed']
if k in dictA)
# Result
print("Dictionary with given keys is : ",res) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given dictionary : {'Sun': '2 PM', 'Tue': '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'}
Dictionary with given keys is : {'Fri': '9 PM', 'Wed': '3 PM'}