0

I have a question regarding a dictionary in python and empty values. If I had the following dictionary

my_dict={'a':[],
 'b':[1],
 'c':[],
 'd':[]
}

How I could remove empty values [] and appending the keys in an empty list?

my_dict={
 'b':[1],
}

and empty_list=['a','c','d']. With a list I would do as follows (but there are several ways to do the same):

my_dict = list(filter(None, my_dict)) 

But I have realised I do not know how to do the same in a dictionary.

  • 1
    `{k:v for k,v in my_dict.items() if v is not None}`? – yatu Oct 11 '20 at 18:25
  • Hi Marcin, it answers partially. I am still not understand how to remove empty values :( –  Oct 11 '20 at 18:25
  • thanks @yatu. I have not tried it yet. Thanks a lot –  Oct 11 '20 at 18:26
  • seriously, sometimes it is hard for me to understand the reason why some questions are down voted and some others (with no reproducible data, no attempt of solution, ...) are not :/ –  Oct 11 '20 at 18:43

2 Answers2

1

You can use a dict comprehension to remove empty values:

new_dict = {k: v for k, v in my_dict.items() if v}

Then you can use set difference to get the removed keys:

removed_keys = my_dict.keys() - new_dict.keys()
a_guest
  • 34,165
  • 12
  • 64
  • 118
0

Just do two explicit iterations for a clean solution -- first calculate the empty_list, then filter down my_dict:

empty_list = [k for k, v in my_dict.items() if len(v) == 0]
my_dict = {k: v for k, v in my_dict.items() if len(v) != 0}
Cihan
  • 2,267
  • 8
  • 19