Copy a dictionary, except some keys

How common is the need of getting a copy of a dict, except some of its keys?

It happens to me quite frequently that I need a similar dict to what I have, but without some of its keys. Of course I can’t just remove the keys, as other parts of the code still uses the full dict.

I end up doing stuff like this:

new_dict = {k: v for k, v in old_dict.items() if k not in {'key1', 'key2'}}

What if we could do just…?

new_dict = old_dict.copy(avoid_keys=('key1', 'key2'))  

Alternatives:

new_dict = old_dict.copy(avoid=('key1', 'key2'))  
new_dict = old_dict.copy(except=('key1', 'key2'))  

Thanks!

1 Like