-1

I have a dict where the values are a list of strings. Some values in this list are empty (like empty string). Now I need the dict with all the keys as original but want to remove the empty values from the list. Could someone please help as I think it can be done using filter() for lists in python. Below is an example of the original and final dict required

original_dict = {"abc": ["","red","green","blue"], "def":["amber","silver","","gold","black","",""]}
output_dict = {"abc": ["red","green","blue"], "def":["amber","silver","gold","black"]}
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
Vortex
  • 45
  • 4
  • Might not be relevant here, but if you are creating this dict, a better question could be how to avoid those empty strings in the first place... – Tomerikoo Jul 19 '22 at 12:58
  • I checked the above related question, and it does not answer the query that I had. The above link only mentions about lists and not lists in a dict. – Vortex Jul 19 '22 at 15:20
  • What you want is to change lists. They just happen to be values in a dict. Modifying values in a dict is a simple task surely answered here as well – Tomerikoo Jul 19 '22 at 22:11

2 Answers2

1

Nested comprehensions will let you make a new dict:

original_dict = {"abc": ["","red","green","blue"], "def":["amber","silver","","gold","black","",""]}
output_dict = {k: [x for x in v if x] for k, v in original_dict.items()}

If you want to modify the original dict and its lists in place (so aliases see all changes, whether they alias the dict or the contained lists), you can avoid touching the keys and just replace the contents of each list with the pruned version, like so:

for v in original_dict.values():
     v[:] = [x for x in v if x]  # Or v[:] = filter(None, v) if you prefer

The [:] in there is what makes even aliases of the lists get changed. If you didn't want to change them in-place, you'd need the keys (to enable reassignment) and you'd instead do:

for k, v in original_dict.items():
     original_dict[k] = [x for x in v if x]
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1
for k,v in original_dict.items():
    original_dict[k] = list(filter(None, v))
paras chauhan
  • 777
  • 4
  • 13