I want to make a function that returns a copy of a dictionary excluding keys specified in a list.
Considering this dictionary:
JavaScript
x
6
1
my_dict = {
2
"keyA": 1,
3
"keyB": 2,
4
"keyC": 3
5
}
6
A call to without_keys(my_dict, ['keyB', 'keyC'])
should return:
JavaScript
1
4
1
{
2
"keyA": 1
3
}
4
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
1
3
1
def without_keys(d, keys):
2
return {k: d[f] if k not in keys for f in d}
3
which is invalid syntax. How can I do this?
Advertisement
Answer
You were close, try the snippet below:
JavaScript
1
11
11
1
>>> my_dict = {
2
"keyA": 1,
3
"keyB": 2,
4
"keyC": 3
5
}
6
>>> invalid = {"keyA", "keyB"}
7
>>> def without_keys(d, keys):
8
return {x: d[x] for x in d if x not in keys}
9
>>> without_keys(my_dict, invalid)
10
{'keyC': 3}
11
Basically, the if k not in keys
will go at the end of the dict comprehension in the above case.