Bird
Raised Fist0
Pythonprogramming~10 mins

Accessing values using keys in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Accessing values using keys
Start with dictionary
Provide key to access
Check if key exists
Return value
End
This flow shows how a dictionary value is accessed by a key: check if the key exists, then return the value or handle missing key.
Execution Sample
Python
my_dict = {'apple': 5, 'banana': 3}
value = my_dict['apple']
print(value)
This code gets the value for key 'apple' from the dictionary and prints it.
Execution Table
StepActionKey ProvidedKey Exists?Value RetrievedOutput
1Create dictionary--{'apple': 5, 'banana': 3}-
2Access value'apple'Yes5-
3Print value---5
💡 Finished accessing and printing the value for key 'apple'.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
my_dictundefined{'apple': 5, 'banana': 3}{'apple': 5, 'banana': 3}{'apple': 5, 'banana': 3}
valueundefinedundefined55
Key Moments - 2 Insights
What happens if the key does not exist in the dictionary?
If the key is missing, Python raises a KeyError. This is shown by the 'Key Exists?' check in the flow. To avoid errors, use methods like dict.get() or check key presence before access.
Why do we use square brackets [] to access dictionary values?
Square brackets tell Python to look up the value for the given key in the dictionary. This is shown in Step 2 where 'apple' is inside [].
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'value' after Step 2?
Aundefined
B3
C5
DKeyError
💡 Hint
Check the 'Value Retrieved' column at Step 2 in the execution_table.
At which step is the dictionary created?
AStep 2
BStep 1
CStep 3
DAfter Step 3
💡 Hint
Look at the 'Action' column in the execution_table for when the dictionary is created.
If we try to access my_dict['orange'], what would happen?
ARaise KeyError
BReturn 0
CReturn None
DReturn 'orange'
💡 Hint
Recall the 'Key Exists?' decision in the concept_flow and what happens if key is missing.
Concept Snapshot
Access dictionary values using keys with square brackets: value = dict[key]
If key exists, returns the value; else raises KeyError.
Use dict.get(key) to avoid errors and get None or default.
Keys must be immutable types like strings or numbers.
Accessing values is fast and direct.
Full Transcript
This lesson shows how to get values from a dictionary using keys. We start with a dictionary that stores pairs of keys and values. To get a value, we provide the key inside square brackets. Python checks if the key exists. If yes, it returns the value. If not, it raises an error. The example code creates a dictionary with fruits and counts, then gets the count for 'apple' and prints it. Variables change as the dictionary is created and the value is retrieved. Beginners often wonder what happens if the key is missing or why square brackets are used. The quiz asks about variable values at steps and what happens with missing keys. Remember, use dict.get() to safely access keys that might not exist.

Practice

(1/5)
1. What is the correct way to access the value associated with the key 'name' in the dictionary person = {'name': 'Alice', 'age': 30}?
easy
A. person.get('age')
B. person.name
C. person['name']
D. person['Alice']

Solution

  1. Step 1: Identify the dictionary and key

    The dictionary is person and the key to access is 'name'.
  2. Step 2: Use correct syntax to access value by key

    In Python, dictionary values are accessed using square brackets and the key as a string: person['name'].
  3. Final Answer:

    person['name'] -> Option C
  4. Quick Check:

    Access value by key = person['name'] [OK]
Hint: Use square brackets with the key string to get value [OK]
Common Mistakes:
  • Using dot notation like person.name (not valid for dict)
  • Using a value instead of key inside brackets
  • Accessing a different key than asked
2. Which of the following is the correct syntax to safely get the value for key 'city' from dictionary data without causing an error if the key does not exist?
easy
A. data['city']
B. data.get('city')
C. data.city
D. data['City']

Solution

  1. Step 1: Understand safe access in dictionaries

    Using data['city'] causes an error if the key is missing. Using data.get('city') returns None instead.
  2. Step 2: Identify correct method for safe access

    The get() method is designed to safely access keys without errors.
  3. Final Answer:

    data.get('city') -> Option B
  4. Quick Check:

    Safe key access = data.get('city') [OK]
Hint: Use get() to avoid errors if key missing [OK]
Common Mistakes:
  • Using square brackets which raise KeyError if key missing
  • Using dot notation which is invalid for dict
  • Using wrong key case causing KeyError
3. What will be the output of this code?
info = {'a': 1, 'b': 2, 'c': 3}
print(info['b'])
medium
A. 2
B. 1
C. 3
D. KeyError

Solution

  1. Step 1: Identify the dictionary and key accessed

    The dictionary info has key 'b' with value 2.
  2. Step 2: Access the value using the key

    The code prints info['b'], which is 2.
  3. Final Answer:

    2 -> Option A
  4. Quick Check:

    info['b'] = 2 [OK]
Hint: Look up the key's value directly in the dictionary [OK]
Common Mistakes:
  • Confusing key with value
  • Expecting KeyError when key exists
  • Mixing up keys and values
4. The following code causes an error. What is the problem?
data = {'x': 10, 'y': 20}
print(data['z'])
medium
A. TypeError because keys must be integers
B. SyntaxError due to wrong brackets
C. No error, prints 0
D. KeyError because 'z' is not in the dictionary

Solution

  1. Step 1: Check if key exists in dictionary

    The key 'z' is not present in data.
  2. Step 2: Understand error caused by missing key

    Accessing a missing key with square brackets raises a KeyError.
  3. Final Answer:

    KeyError because 'z' is not in the dictionary -> Option D
  4. Quick Check:

    Missing key access = KeyError [OK]
Hint: Check if key exists before accessing or use get() [OK]
Common Mistakes:
  • Assuming missing keys return 0 or None
  • Confusing syntax error with runtime error
  • Using wrong bracket types
5. Given the dictionary grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}, which code snippet correctly prints Bob's grade or 'Not found' if Bob is not in the dictionary?
hard
A. print(grades.get('Bob', 'Not found'))
B. print(grades['Bob'] or 'Not found')
C. print(grades['bob'] or 'Not found')
D. print(grades.get('Bob'))

Solution

  1. Step 1: Understand the goal

    We want to print Bob's grade if present, otherwise print 'Not found'.
  2. Step 2: Analyze each option

    print(grades['Bob'] or 'Not found') will raise KeyError if key missing because access happens before 'or'. print(grades.get('Bob', 'Not found')) uses get() with default value, which is concise and safe. print(grades['bob'] or 'Not found') uses wrong key case and will fail. print(grades.get('Bob')) prints None if key missing, not 'Not found'.
  3. Final Answer:

    print(grades.get('Bob', 'Not found')) -> Option A
  4. Quick Check:

    Use get() with default for safe access [OK]
Hint: Use get(key, default) to handle missing keys easily [OK]
Common Mistakes:
  • Using wrong key case causing missing key
  • Not providing default value in get()
  • Assuming or operator works for missing keys