I am a novice when it comes to using Python language. I want to understand why removing an item from a dictionary using the del
keyword is impossible when someone references the item using a variable. It seems the del
keyword only works if one uses the square bracket format i.e del dictionary[key
] why is this so? I have provided a code snippet to help in understanding my question and guidance when it comes to answering the question (don't forget to mention the concept of id).
>>> personal_details = {'f_name': 'Imani', 'l_name': 'Ritcher', 'age': 25}
>>> first_name = personal_details['f_name']
>>> id(first_name)
139769037520176
>>> id(personal_details['f_name'])
139769037520176
>>> del first_name
>>> personal_details
{'f_name': 'Imani', 'l_name': 'Ritcher', 'age': 25}
>>> first_name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'first_name' is not defined
>>> del personal_details['f_name']
>>> personal_details
{'l_name': 'Ritcher', 'age': 25}
>>>