Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

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

{     "keyA": 1 } 

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

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?

like image 684
Juicy Avatar asked Jul 15 '15 14:07

Juicy


People also ask

What dictionary method is used to return a duplicate of the dictionary?

The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.

How do you remove key marks from a dictionary?

To delete a key, value pair in a dictionary, you can use the del method. A disadvantage is that it gives KeyError if you try to delete a nonexistent key. So, instead of the del statement you can use the pop method. This method takes in the key as the parameter.

Which function is used to return a shallow copy of a dictionary?

Use dict() The built-in dict() function can be used to make a shallow copy of a dictionary. This function will take the dictionary to be copied as an argument and return a shallow copy of that dictionary.

What does dictionary get return if key not found?

If given key does not exists in dictionary, then it returns the passed default value argument. If given key does not exists in dictionary and Default value is also not provided, then it returns None.


2 Answers

You were close, try the snippet 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, the if k not in keys will go at the end of the dict comprehension in the above case.

like image 190
Anshul Goyal Avatar answered Sep 18 '22 17:09

Anshul Goyal


In your dictionary comprehension you should be iterating over your dictionary (not k , not sure what that is either). Example -

return {k:v for k,v in d.items() if k not in keys} 
like image 30
Anand S Kumar Avatar answered Sep 19 '22 17:09

Anand S Kumar