Delete a dictionary key that has a specific meaning

I know that the dictionary is not intended to be used in this way, so there is no built-in function to create it, but I need to delete every entry in my dictionary that has a specific meaning.

so if my dictionary looks like this:

'NameofEntry1': '0' 'NameofEntry2': 'DNC' ... 

I need to delete (possibly pop) all entries that have a DNC value, there are several in the dictionary.

+4
source share
4 answers

Change the original dict:

 for k,v in your_dic.items(): if v == 'DNC': del your_dic[k] 

or create a new dict using dict comprehension:

 your_dic = {k:v for k,v in your_dic.items() if v != 'DNC'} 

From docs to iteritems() , iterkeys() and itervalues() :

Using iteritems() , iterkeys() or itervalues() when adding or deleting entries in a dictionary can lead to a RuntimeError or crash to iterate over all entries.

The same goes for the normal for key in dic: loop.

In Python 3, this applies to dict.keys() , dict.values() and dict.items() .

+13
source

You just need to make sure that you do not change the dictionary during iteration over it, otherwise you will get RuntimeError: dictionary changed size during iteration .

So, you need to d.items() over a copy of keys, values ​​(for d use d.items() in 2.x or list(d.items()) in 3.x)

 >>> d = {'NameofEntry1': '0', 'NameofEntry2': 'DNC'} >>> for k,v in d.items(): ... if v == 'DNC': ... del d[k] ... >>> d {'NameofEntry1': '0'} 
+3
source

This should work:

 for key, value in dic.items(): if value == 'DNC': dic.pop(key) 
+1
source

If the restrictions are re: changing the dictionary during iteration on it is a problem, you can create a new dict-compatible class that stores the inverse index of all keys that have a given value (updated when creating / updating / deleting a dict item), which can be arguments for del without repeating dict elements.

Subclass dict and override __setitem__ , __delitem__ , pop , popitem and clear .

If this is an operation that you do a lot, it can be convenient and fast.

0
source

Source: https://habr.com/ru/post/1486098/


All Articles