Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to remove the key 'b' from the dictionary.
Python
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.[1]('b')
print(my_dict) Drag options to blanks, or click blank then click option'
Attempts:
3 left
๐ก Hint
Common Mistakes
Using list methods like remove() which do not exist for dictionaries.
Trying to use delete which is not a dictionary method.
โ Incorrect
The pop method removes a key from a dictionary and returns its value.
2fill in blank
mediumComplete the code to remove the key 'x' safely without error if it does not exist.
Python
data = {'x': 10, 'y': 20}
removed = data.[1]('x', None)
print(data, removed) Drag options to blanks, or click blank then click option'
Attempts:
3 left
๐ก Hint
Common Mistakes
Using remove() which is not a dictionary method.
Using del statement which raises error if key missing.
โ Incorrect
The pop method can take a default value to avoid errors if the key is missing.
3fill in blank
hardFix the error in the code to remove the key 'k' from the dictionary.
Python
d = {'k': 5, 'm': 7}
d.[1]('k')
print(d) Drag options to blanks, or click blank then click option'
Attempts:
3 left
๐ก Hint
Common Mistakes
Using remove() which is for lists, not dictionaries.
Trying to use delete which is not a method.
โ Incorrect
pop is the correct method to remove a key from a dictionary.
4fill in blank
hardFill both blanks to remove all keys with values less than 5 from the dictionary.
Python
d = {'a': 3, 'b': 7, 'c': 2}
for key in list(d.[1]()):
if d[key] [2] 5:
d.pop(key)
print(d) Drag options to blanks, or click blank then click option'
Attempts:
3 left
๐ก Hint
Common Mistakes
Using items() without unpacking keys and values.
Using greater than operator instead of less than.
โ Incorrect
Use keys() to iterate over keys and remove those with values less than 5 using <.
5fill in blank
hardFill all three blanks to create a new dictionary excluding entries with value 0.
Python
original = {'x': 0, 'y': 5, 'z': 0}
filtered = { [1]: [2] for [3] in original.items() if [2] != 0 }
print(filtered) Drag options to blanks, or click blank then click option'
Attempts:
3 left
๐ก Hint
Common Mistakes
Using only one variable to unpack items.
Using wrong variable names inconsistently.
โ Incorrect
Use k, v to unpack items, then build a dictionary with keys k and values v excluding zeros.