0% completed
Dictionaries store key-value pairs, allowing fast lookups of values using keys. To access elements in a dictionary, you use:
[]
– Directly retrieves the value associated with a key.get()
method – A safer way to access values, as it prevents errors if a key is missing.Using dictionaries for data retrieval is faster than searching through lists or tuples, making them ideal for applications requiring quick lookups, such as caching, configurations, and data processing.
Square brackets []
allow retrieving values directly using keys. However, attempting to access a non-existent key results in a KeyError
.
student_ages["Alice"]
retrieves the value associated with "Alice"
, which is 22
.KeyError
.The get()
method retrieves values like []
but provides a default value when the key is missing, preventing errors.
student_ages.get("Bob")
returns 25
, the value for "Bob"
.[]
, get()
does not raise an error if the key is missing.You can provide a default value with get()
to handle missing keys gracefully.
get("Charlie", "Not Found")
returns "Not Found"
instead of raising an error......
.....
.....