Question on 'del'


12. changing your mind

i got this to work, i was wondering if the following is allowed, i didn't see anything in google

del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']

to: del zoo_animals['Sloth', 'Bengal Tiger']

tried the combined way, it didn't work,, went to the single lines, that worked

Replace this line with your code. 

del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']


If you ever want to do single line way:

del zoo_animals['Sloth'], zoo_animals['Bengal Tiger']


As you observe, del can only remove one key/value at a time.

KeyError: ('Sloth', 'Bengal Tiger')

Since dictionaries are unordered, we cannot specify a range (slice) for multiple deletes.


It works, but is suspect of introducing errors. It would take more structure but from a reader perspective a function with a list parameter would be more explicit.

def del_keys(obj,keys):
    for key in keys:
        del obj[key]

This is just opinion, mind.


THANKS for showing me how to do this.


thanks for your time..


Ah, I'll have to look into this a bit more. Thanks for the heads up.
When @jackhg mentioned about how they couldn't find anything on Google about this, I suspect that it isn't a great way to do this. I forgot how I discovered this :sweat_smile:


thanks, keep telling and showing me this works, in my case it doesn't
work, that's ok, i'll keep on trying..and sometimes i actually get it to

i really appreciate your time..

jack g


Given this dictionary,

zoo_animals = { 
    'Unicorn' : 'Cotton Candy House',
    'Sloth' : 'Rainforest Exhibit',
    'Bengal Tiger' : 'Jungle House',
    'Atlantic Puffin' : 'Arctic Exhibit',
    'Rockhopper Penguin' : 'Arctic Exhibit'

>>> del zoo_animals['Sloth']
>>> zoo_animals
{'Bengal Tiger': 'Jungle House', 'Unicorn': 'Cotton Candy House', 'Atlantic Puffin': 'Arctic Exhibit', 'Rockhopper Penguin': 'Arctic Exhibit'}
>>> del zoo_animals['Bengal Tiger']
>>> zoo_animals
{'Unicorn': 'Cotton Candy House', 'Atlantic Puffin': 'Arctic Exhibit', 'Rockhopper Penguin': 'Arctic Exhibit'}


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.