Which of the following is an invalid method / function in a Python dictionary?
2023
Which of the following is an invalid method / function in a Python dictionary?
- A.
popitem()
- B.
remove()
- C.
get()
- D.
pop()
Attempted by 1708 students.
Show answer & explanation
Correct answer: B
Answer: remove() is not a method of Python dictionaries.
Why remove() is invalid for dictionaries: The remove() method exists for lists and sets, not for dict objects. Calling remove() on a dictionary raises an AttributeError. To remove keys from a dictionary, use pop(key[, default]) or the del statement.
Useful dictionary methods (examples):
pop(key[, default]) — removes the specified key and returns its value. If the key is missing and no default is given, a KeyError is raised. Example: mydict.pop('a', None).
popitem() — removes and returns a key-value pair. In Python 3.7+ it removes the last inserted pair. Useful when you need any item and its value.
get(key[, default]) — returns the value for key if present, otherwise returns None or the specified default. Does not raise an error for missing keys.
Summary: remove() is not a dictionary method. Use pop(), popitem(), get(), or del to work with dictionary entries.