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

ดึงค่า Value จาก Dictionary ถ้า Key อยู่ใน List และ Dict ทั้งคู่

แนวคิด

ตรวจสอบว่า key K อยู่ใน list และเป็น key ใน dictionary ทั้งคู่ ถ้าใช่ ให้คืนค่า value จาก dictionary

ตัวอย่างโค้ด

my_list = ["Python", "is", "fun", "to", "learn", "and", "teach", "cool", "object", "oriented"]
my_dict = {"Python": 2, "fun": 4, "learn": 6}
K = "Python"

print("K =", K)
print("List:", my_list)
print("Dict:", my_dict)

# ใช้ all() ตรวจสอบ K อยู่ในทั้งสอง
my_result = None
if all(K in container for container in [my_list, my_dict]):
    my_result = my_dict[K]

print("ผลลัพธ์:", my_result)

ผลลัพธ์

K = Python
List: ['Python', 'is', 'fun', 'to', 'learn', 'and', 'teach', 'cool', 'object', 'oriented']
Dict: {'Python': 2, 'fun': 4, 'learn': 6}
ผลลัพธ์: 2

คำอธิบาย

  • all(K in container for container in [my_list, my_dict]) ตรวจสอบ K ใน list และใน dict keys
  • สำหรับ dict, K in my_dict ตรวจสอบ key (เทียบเท่า K in my_dict.keys())
  • ถ้า True -> ดึง my_dict[K]

ขยาย: หลาย Keys

keys_to_check = ["Python", "fun", "java"]
result = {k: my_dict[k] for k in keys_to_check if k in my_list and k in my_dict}
print(result)  # {'Python': 2, 'fun': 4}