Bird
Raised Fist0
Pythonprogramming~10 mins

Safe access using get() in Python - Interactive Code Practice

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to safely get the value for key 'name' from the dictionary.

Python
person = {'name': 'Alice', 'age': 30}
name = person.[1]('name')
print(name)
Drag options to blanks, or click blank then click option'
Aget
Bpop
Ckeys
Dvalues
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using person['name'] which causes error if key is missing
Using pop which removes the key from dictionary
2fill in blank
medium

Complete the code to get the value for 'city' with a default of 'Unknown'.

Python
location = {'country': 'USA'}
city = location.[1]('city', 'Unknown')
print(city)
Drag options to blanks, or click blank then click option'
Aget
Bpop
Csetdefault
Dupdate
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using pop which removes the key
Using setdefault which adds the key if missing
3fill in blank
hard

Fix the error by completing the code to safely access 'score' from the dictionary.

Python
results = {'player': 'Bob'}
score = results.[1]('score')
print(score)
Drag options to blanks, or click blank then click option'
Aclear
Bget
Cpopitem
Dkeys
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using popitem which removes an arbitrary item
Using keys which returns all keys, not a value
4fill in blank
hard

Fill both blanks to create a dictionary of word lengths only for words longer than 3 letters.

Python
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if [2] > 3}
Drag options to blanks, or click blank then click option'
Alen(word)
Bword
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using word instead of len(word) for length
Checking word instead of its length in condition
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase keys and values only if value is positive.

Python
data = {'a': 1, 'b': -2, 'c': 3}
result = { [1]: [2] for k, v in data.items() if v [3] 0 }
Drag options to blanks, or click blank then click option'
Ak.upper()
Bv
C>
Dk
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using original key instead of uppercase
Using wrong comparison operator
Using key instead of value for dictionary values

Practice

(1/5)
1. What does the get() method do when used with a Python dictionary?
easy
A. It safely returns the value for a given key or a default if the key is missing.
B. It deletes the key-value pair from the dictionary.
C. It adds a new key-value pair to the dictionary.
D. It returns all keys in the dictionary.

Solution

  1. Step 1: Understand dictionary access

    Accessing a key directly can cause an error if the key doesn't exist.
  2. Step 2: Role of get()

    The get() method returns the value if the key exists, else returns a default value without error.
  3. Final Answer:

    It safely returns the value for a given key or a default if the key is missing. -> Option A
  4. Quick Check:

    Safe dictionary access = get() method [OK]
Hint: Remember: get() avoids errors by returning default if key missing [OK]
Common Mistakes:
  • Thinking get() deletes keys
  • Confusing get() with adding keys
  • Assuming get() returns all keys
2. Which of the following is the correct syntax to safely get the value of key 'age' from dictionary person with default 30?
easy
A. person.get('age', 30)
B. person['age', 30]
C. person.get('age': 30)
D. person.get['age', 30]

Solution

  1. Step 1: Recall get() method syntax

    The correct syntax is dict.get(key, default) with parentheses and comma.
  2. Step 2: Check each option

    person.get('age', 30) uses correct parentheses and comma. Others have wrong brackets or colon.
  3. Final Answer:

    person.get('age', 30) -> Option A
  4. Quick Check:

    Correct get() syntax uses parentheses and comma [OK]
Hint: Use parentheses and comma: dict.get(key, default) [OK]
Common Mistakes:
  • Using square brackets instead of parentheses
  • Using colon instead of comma
  • Missing parentheses
3. What is the output of this code?
data = {'name': 'Alice', 'city': 'Paris'}
print(data.get('age', 25))
medium
A. Alice
B. KeyError
C. None
D. 25

Solution

  1. Step 1: Check if 'age' key exists in dictionary

    The dictionary has keys 'name' and 'city', but no 'age'.
  2. Step 2: Understand get() with default

    Since 'age' is missing, get() returns the default value 25.
  3. Final Answer:

    25 -> Option D
  4. Quick Check:

    Missing key returns default value [OK]
Hint: Missing key? get() returns default value, not error [OK]
Common Mistakes:
  • Expecting KeyError instead of default
  • Confusing key 'age' with 'name'
  • Assuming None is returned by default
4. Find the error in this code snippet:
info = {'color': 'blue'}
print(info.get['color', 'red'])
medium
A. Key 'color' does not exist in dictionary
B. Missing default value in get()
C. Using square brackets [] instead of parentheses () with get()
D. Syntax error due to missing colon

Solution

  1. Step 1: Identify get() method call syntax

    The get() method requires parentheses, not square brackets.
  2. Step 2: Analyze the code

    Using square brackets causes a TypeError because get is a method, not a subscriptable object.
  3. Final Answer:

    Using square brackets [] instead of parentheses () with get() -> Option C
  4. Quick Check:

    get() needs parentheses, not brackets [OK]
Hint: Always call get() with parentheses, not brackets [OK]
Common Mistakes:
  • Using brackets instead of parentheses
  • Assuming missing key causes error
  • Confusing syntax errors with key errors
5. You have a dictionary settings = {'theme': 'dark', 'font': None}. You want to get the font setting but use 'Arial' if the font is missing or set to None. Which code correctly does this?
hard
A. font = settings.get('font', 'Arial')
B. font = settings.get('font', 'Arial') or 'Arial'
C. font = settings['font'] if 'font' in settings else 'Arial'
D. font = settings.get('font') if settings['font'] else 'Arial'

Solution

  1. Step 1: Understand the problem

    The key 'font' exists but its value is None, which is falsy.
  2. Step 2: Analyze each option

    font = settings.get('font', 'Arial') or 'Arial' uses get() with default 'Arial' and then or 'Arial' to handle None value. This ensures 'Arial' is used if value is None or missing.
    font = settings.get('font', 'Arial') returns None because 'font' exists but is None.
    font = settings['font'] if 'font' in settings else 'Arial' checks key existence but does not handle None value.
    font = settings.get('font') if settings['font'] else 'Arial' causes error if 'font' key is missing.
  3. Final Answer:

    font = settings.get('font', 'Arial') or 'Arial' -> Option B
  4. Quick Check:

    Use get() with default and or to handle None [OK]
Hint: Use get() with default plus or to handle None values [OK]
Common Mistakes:
  • Assuming get() default handles None values
  • Not checking for None explicitly
  • Using key access without checking existence