The returned copy of the dictionary, excluding the specified keys

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

Given this dictionary:

my_dict = { "keyA": 1, "keyB": 2, "keyC": 3 } 

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

 { "keyA": 1 } 

I would like to do this on one line with a neat understanding of the word, but I have problems. My attempt:

 def without_keys(d, keys): return {k: d[f] if k not in keys for f in d} 

which is invalid syntax. How can i do this?

+5
source share
4 answers

You were near, try the picture below:

 >>> my_dict = { ... "keyA": 1, ... "keyB": 2, ... "keyC": 3 ... } >>> invalid = {"keyA", "keyB"} >>> def without_keys(d, keys): ... return {x: d[x] for x in d if x not in keys} >>> without_keys(my_dict, invalid) {'keyC': 3} 

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

+9
source

This should work for you.

 def without_keys(d, keys): return {k: v for k, v in d.items() if k not in keys} 
+3
source

In your understanding of the word, you should iterate through your dictionary (not k , not sure what it is). Example -

 return {k:v for k,v in d.items() if k not in keys} 
+3
source

For those who don't like lists, this is my version:

 def without_keys(d, *keys): dict(filter(lambda key_value: key_value[0] not in keys, d.items())) 

Using:

 >>> d={1:3, 5:7, 9:11, 13:15} >>> without_keys(d, 1, 5, 9) {13: 15} >>> without_keys(d, 13) {1: 3, 5: 7, 9: 11} >>> without_keys(d, *[5, 7]) {1: 3, 13: 15, 9: 11} 
0
source

All Articles