-2

I have a dictionary composed of multiple key. Is has been created by a loop so the keys generated at the beginning don't have values but, I fill them later. Sometimes, a key is not filled so I want to remove it from the dictionary

The dictionary look like:

{'a' : [1,2,3,4] , 'b' : [5,6,7,8] ,'c': [] ,'d': [9,10,11]}

I may have multiple values that look like 'c' i have tried the try/except but still get the "dictionary changed size during iteration"

d= {'a' : [1,2,3,4] , 'b' : [5,6,7,8] ,'c': [] ,'d': [9,10,11]}
dic_key = d.keys()
for key in dic_key:
         try:
             if len(d[key]) == 0:
                    del d[key]
         except:
             pass

"dictionary changed size during iteration"

  • yup @Sayse, definitely a duplicate of at least the second one – Adam.Er8 Jun 20 '19 at 15:43
  • You shouldn't modify an iterable you're looping through. Either create a second dictionary so you can have one dictionary to iterate over and another to modify, or use a comprehension. – Acccumulation Jun 20 '19 at 16:00

1 Answers1

1

use dict comprehension:

try this:

d = {k:v for k,v in d.items() if len(v)}
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38