dublintech dublintech - 1 year ago 379
Python Question

Removing multiple keys from a dictionary safely

I know to remove an entry, 'key' from my dictionary

, safely, you do:

if d.has_key('key'):
del d['key']

However, I need to remove multiple entries from dictionary safely. I was thinking of defining the entries in a tuple as I will need to do this more than once.

entitiesToREmove = ('a', 'b', 'c')
for x in entitiesToRemove:
if d.has_key(x):
del d[x]

However, I was wondering if there is a smarter way to do this?

Answer Source

Why not like this:

entries = ('a', 'b', 'c')
the_dict = {'b': 'foo'}

def entries_to_remove(entries, the_dict):
    for key in entries:
        if key in the_dict:
            del the_dict[key]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download