Removing unanswered posts - Python

If I have a dictionary and I want to delete entries in which this value is an empty list [] , how would I do it?

I tried:

 for x in dict2.keys(): if dict2[x] == []: dict2.keys().remove(x) 

but it didn’t work.

+7
source share
8 answers

.keys() provides access to the list of keys in the dictionary, but changes to it are not (necessarily) reflected in the dictionary. To delete it, use del dictionary[key] or dictionary.pop(key) .

Due to the behavior in some version of Python, you need to create a copy of your keys list so that everything can work correctly. Thus, your code will work if it is written as:

 for x in list(dict2.keys()): if dict2[x] == []: del dict2[x] 
+12
source

Newer versions of python support support:

 dic = {i:j for i,j in dic.items() if j != []} 

They are more readable than a filter or for loops.

+10
source
 for x in dict2.keys(): if dict2[x] == []: del dict2[x] 
+3
source

Why not just save the ones that are not empty and let gc remove the leftovers? I mean:

 dict2 = dict( [ (k,v) for (k,v) in dict2.items() if v] ) 
+2
source
 for key in [ k for (k,v) in dict2.items() if not v ]: del dict2[key] 
+1
source

Clear one, but it will create a copy of this dict:

 dict(filter(lambda x: x[1] != [], d.iteritems())) 
+1
source

With a generator object instead of a list:

 a = {'1': [], 'f':[1,2,3]} dict((data for data in a.iteritems() if data[1])) 
+1
source
 def dict_without_empty_values(d): return {k:v for k,v in d.iteritems() if v} # Ex; dict1 = { 'Q': 1, 'P': 0, 'S': None, 'R': 0, 'T': '', 'W': [], 'V': {}, 'Y': None, 'X': None, } print dict1 # {'Q': 1, 'P': 0, 'S': None, 'R': 0, 'T': '', 'W': [], 'V': {}, 'Y': None, 'X': None} print dict_without_empty_values(dict1) # {'Q': 1} 
0
source

All Articles