Copy a dictionary, except some keys

You can make your dict comprehension more concise by using the keys() dictionary view:

new_dict = {k: old_dict[k] for k in old_dict.keys() - {'key1', 'key2'}}

These act like sets, so you can use set subtraction.

I agree with Brett that I can’t see this being common enough to complicate the dict.copy() method.

2 Likes