Safely remove multiple keys from a dictionary

I know to remove the entry, the "key" from my d dictionary, safely:

 if d.has_key('key'): del d['key'] 

However, I need to delete multiple entries from the dictionary safely. I was thinking about defining records in a tuple, since I will need to do this more than once.

 entitiesToREmove = ('a', 'b', 'c') for x in entitiesToRemove: if d.has_key(x): del d[x] 

However, I was wondering if there is a more reasonable way to do this?

+86
python dictionary
Jan 24 2018-12-12T00:
source share
10 answers

Why not:

 entries = ('a', 'b', 'c') the_dict = {'b': 'foo'} def entries_to_remove(entries, the_dict): for key in entries: if key in the_dict: del the_dict[key] 

A more compact version was provided by Materborns using dict.pop ()

+36
Jan 24 '12 at 23:20
source share
 d = {'some':'data'} entriesToRemove = ('any', 'iterable') for k in entriesToRemove: d.pop(k, None) 
+173
Jan 24 '12 at 23:22
source share

Using Dict Comprehensions

 final_dict = {key: t[key] for key in t if key not in [key1, key2]} 

where key1 and key2 should be removed.

In the example below, the keys "b" and "c" should be deleted and stored in the key list.

 >>> a {'a': 1, 'c': 3, 'b': 2, 'd': 4} >>> keys = ["b", "c"] >>> print {key: a[key] for key in a if key not in keys} {'a': 1, 'd': 4} >>> 
+69
Jan 24 '12 at 23:25
source share

If you also need to get the values ​​for the keys that you delete, this would be a good way:

 valuesRemoved = [d.pop(k, None) for k in entitiesToRemove] 

Of course, you could only do this to remove keys from d , but you would not have to create a list of values ​​with a list. It’s also a little confusing to use list comprehension only as a side effect of a function.

+17
Jan 24 '12 at 23:27
source share

the solution uses map and filter functions

python 2

 d={"a":1,"b":2,"c":3} l=("a","b","d") map(d.__delitem__, filter(d.__contains__,l)) print(d) 

python 3

 d={"a":1,"b":2,"c":3} l=("a","b","d") list(map(d.__delitem__, filter(d.__contains__,l))) print(d) 

You get:

 {'c': 3} 
+13
May 20 '15 at 1:35 pm
source share

I have no problem with any of the existing answers, but I was surprised when I did not find this solution:

 keys_to_remove = ['a', 'b', 'c'] my_dict = {k: v for k, v in zip("abcdefg".split(' '), [0, 1, 2, 3, 4, 5, 6])} for k in keys_to_remove: try: del my_dict[k] except KeyError: pass assert my_dict == {'d': 3, 'e': 4, 'f': 5, 'g': 6} 

Note. I came across this question coming from here . And my answer is related to this answer .

+4
May 20, '15 at 13:37
source share

Why not:

 entriestoremove = (2,5,1) for e in entriestoremove: if d.has_key(e): del d[e] 

I don’t know what you mean by the “smarter way”. Of course, there are other ways, perhaps with an understanding of the dictionary:

 entriestoremove = (2,5,1) newdict = {x for x in d if x not in entriestoremove} 
+2
Jan 24 '12 at 23:20
source share

in-line

 import functools #: not key(c) in d d = {"a": "avalue", "b": "bvalue", "d": "dvalue"} entitiesToREmove = ('a', 'b', 'c') #: python2 map(lambda x: functools.partial(d.pop, x, None)(), entitiesToREmove) #: python3 list(map(lambda x: functools.partial(d.pop, x, None)(), entitiesToREmove)) print(d) # output: {'d': 'dvalue'} 
+1
Oct 27 '16 at 5:14
source share

I'm late for this discussion, but for someone else. The solution may be to create a list of keys as such.

 k = ['a','b','c','d'] 

Then use the pop () function in a list comprehension or for a loop to iterate over the keys and sweat one at a time as such.

 new_dictionary = [dictionary.pop(x, 'n/a') for x in k] 

"N / a" in case the key does not exist, you must return the default value.

0
May 16 '18 at 10:55
source share

I was late, but found a solution with pop map and map

 d = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'} keys = ['a', 'b', 'c'] list(map(d.pop, keys)) print(d) 

The output of this:

 {'d': 'valueD'} 
0
Jan 24 '19 at 6:07
source share



All Articles