Kiểm tra dữ liệu trong dictionary
Bạn có thể kiểm tra một key có tồn tại trong dictionary hay không bằng cách dùng biểu thức in.
Ví dụ, bạn có thể kiểm tra xem 'cookies' có phải là một key trong dictionary recipes hay không bằng if 'cookies' in recipes:. Cách này giúp bạn xử lý an toàn khi dữ liệu có mặt trong dictionary.
Chúng tôi đã nạp một dictionary squirrels_by_park với tên công viên làm key và giá trị là một danh sách các dictionary về sóc.
Bài tập này là một phần của khóa học
Các kiểu dữ liệu trong Python
Hướng dẫn bài tập
- Kiểm tra xem
Tompkins Square Parkcó trong dictionarysquirrels_by_parkkhông, và in'Found Tompkins Square Park'nếu có. - Kiểm tra xem
Central Parkcó trongsquirrels_by_parkkhông. Sau đó, in'Found Central Park'nếu tìm thấy và'Central Park missing'nếu không tìm thấy.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# Check to see if Tompkins Square Park is in squirrels_by_park
if "____" ____ ____:
# Print 'Found Tompkins Square Park'
print('Found Tompkins Square Park')
# Check to see if Central Park is in squirrels_by_park
if "____" ____ ____:
# Print 'Found Central Park' if found
print('Found Central Park')
else:
# Print 'Central Park missing' if not found
print('Central Park missing')