Skip to content
Advertisement

Return copy of dictionary excluding specified keys

I want to make a function that returns a copy of a dictionary excluding keys specified in a list.

Considering this dictionary:

JavaScript

A call to without_keys(my_dict, ['keyB', 'keyC']) should return:

JavaScript

I would like to do this in a one-line with a neat dictionary comprehension but I’m having trouble. My attempt is this:

JavaScript

which is invalid syntax. How can I do this?

Advertisement

Answer

You were close, try the snippet below:

JavaScript

Basically, the if k not in keys will go at the end of the dict comprehension in the above case.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement