Accessing Values

  • This lesson teaches how to access values from a dictionary using keys in Python.

  • What Does "Accessing Values" Mean?

    In a dictionary, data is stored as key : value pairs.

    👉 Accessing values means retrieving the data stored inside a dictionary using its key.

    Real-Life Example

    Think of a dictionary as a contact list

    Key (Name)

    Value (Phone Number)

    Ravi

    9876543210

    To get Ravi’s number, you use his name (key).

    Method 1: Using Square Brackets [ ]

    Syntax

    dictionary_name[key]

Access Value Using Key

This example retrieves the student's name using its key.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

print(student["name"])
  • ⚠ Important

    If the key does not exist, Python gives an error:

    print(student["marks"])   # KeyError

  • Method 2: Using get() Method

    The get() method is a safe way to access dictionary values.

    Syntax

    dictionary_name.get(key)

Access Value Using get()

This example safely retrieves a value. If the key doesn't exist, it returns None.

student = {
    "name": "Amit",
    "age": 20
}

print(student.get("name"))
print(student.get("marks"))

Access Nested Dictionary

This example accesses values inside another dictionary.

student = {
    "name": "Riya",
    "marks": {
        "math": 90,
        "science": 88
    }
}

print(student["marks"]["math"])
  •  Difference: [ ] vs get()

    Feature

    [ ]

    get()

    Key not found

    Error ❌

    Returns None ✅

    Safe

    No

    Yes

    Common use

    When sure key exists

    When key may not exist