Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python – ตรวจสอบค่าที่ตรงกับ Key K ในลิสต์ Dictionary

เมื่อต้องการตรวจสอบว่าค่าที่กำหนดมีอยู่ใน key K ของ dictionary ทุกตัวในลิสต์หรือไม่ สามารถใช้ list comprehension ได้

ตัวอย่าง

my_list = [{"python": "14", "is": "great", "fun": "1`"}, {"python": "cool", "is": "fun", "best": "81"}, {"python": "93", "is": "CS", "amazing": "16"}]
print("The list is :")
print(my_list)
K = "python"
print("The value of K is ")
print(K)
value = "cool"
my_result = value in [index[K] for index in my_list]
print("The result is :")
if my_result == True:
    print("The value is present in with respect to key ")
else:
    print("The value isn't present with respect to key")

ผลลัพธ์

The list is : [{'python': '14', 'is': 'great', 'fun': '1`'}, {'python': 'cool', 'is': 'fun', 'best': '81'}, {'python': '93', 'is': 'CS', 'amazing': '16'}]
The value of K is python
The result is : The value is present in with respect to key

คำอธิบาย

  • กำหนดลิสต์ของ dictionary และ key K ที่สนใจ

  • กำหนดค่า value ที่ต้องการค้นหา

  • ใช้ list comprehension ดึงค่าของ key K จากทุก dictionary: [index[K] for index in my_list]

  • ตรวจสอบ value in ... ว่าค่าที่ต้องการอยู่ในลิสต์ค่านั้นหรือไม่

  • แสดงข้อความตามผลลัพธ์ Boolean