Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python – Trích xuất giá trị Key nếu Key có trong cả List và Dictionary

Khi cần lấy giá trị của key nếu key đó có mặt trong cả list và dictionary, ta dùng vòng lặp và toán tử all.

Ví dụ

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

print("Giá trị K:", K)
print("List:", my_list)
print("Dictionary:", my_dictionary)

my_result = None
if all(K in sub for sub in [my_dictionary, my_list]):
    my_result = my_dictionary[K]

print("Kết quả:")
print(my_result)

Kết quả đầu ra

Giá trị K: Python
List: ['Python', 'is', 'fun', 'to', 'learn', 'and', 'teach', 'cool', 'object', 'oriented']
Dictionary: {'Python': 2, 'fun': 4, 'learn': 6}
Kết quả:
2

Giải thích

  • all(K in sub for sub in [my_dictionary, my_list]) kiểm tra K có trong dictionary (kiểm tra key) VÀ trong list (kiểm tra phần tử).
  • Nếu True, gán my_result = my_dictionary[K].
  • K="Python" có trong cả hai → kết quả 2.

Cách viết rõ ràng hơn:

if K in my_dictionary and K in my_list:
    my_result = my_dictionary[K]