Question on 'del'


#1



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']


#2

If you ever want to do single line way:

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

#3

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.


#4

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.


#5

THANKS for showing me how to do this.


#6

thanks for your time..


#7

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:


#8

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
work....

i really appreciate your time..

jack g


#9

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'}
>>>

#10

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