Python From Beginner to Advanced

0% completed

Previous
Next
Python - Accessing Elements from a Dictionary

Dictionaries store key-value pairs, allowing fast lookups of values using keys. To access elements in a dictionary, you use:

  • Square brackets [] – Directly retrieves the value associated with a key.
  • The 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.

1. Accessing Dictionary Elements Using Square Brackets ("[]")

Square brackets [] allow retrieving values directly using keys. However, attempting to access a non-existent key results in a KeyError.

Example 1: Accessing Values Using Square Brackets

Python3
Python3

. . . .

Explanation

  • student_ages["Alice"] retrieves the value associated with "Alice", which is 22.
  • This method works only if the key exists; otherwise, it raises a KeyError.

2. Using "get()" to Access Dictionary Elements

The get() method retrieves values like [] but provides a default value when the key is missing, preventing errors.

Example 2: Accessing Values Using "get()"

Python3
Python3

. . . .

Explanation

  • student_ages.get("Bob") returns 25, the value for "Bob".
  • Unlike [], get() does not raise an error if the key is missing.

3. Using "get()" with a Default Value

You can provide a default value with get() to handle missing keys gracefully.

Example 3: Handling Missing Keys with "get()"

Python3
Python3

. . . .

Explanation

  • get("Charlie", "Not Found") returns "Not Found" instead of raising an error.
  • This is useful when working with dynamic dictionaries where keys might not always exist.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next