forked from balapriyac/python-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
29 lines (22 loc) · 719 Bytes
/
main.py
File metadata and controls
29 lines (22 loc) · 719 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
books = {
"1984": "George Orwell",
"To Kill a Mockingbird": "Harper Lee",
"The Great Gatsby": "F. Scott Fitzgerald"
}
# handle KeyError explicitly
try:
# Try to access the key "Brave New World"
author = books["Brave New World"]
# Catch the KeyError if the key does not exist
except KeyError:
author = "Book not found"
print(author)
# Try to get the value for "Brave New World"
author = books.get("Brave New World", "Book not found")
print(author)
# use defaultdict to handle missing keys natively
from collections import defaultdict
books_default = defaultdict(lambda: "Book not found",books)
# Access the key "Brave New World"
author = books_default["Brave New World"]
print(author)