Hi can anyone tell me how to remove empty keys in the following dictionary

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

I want it to be

d={'b':}


I tried this. But its showing error. I know its wrong to change the size of a dictionary during iteration. But is there any other way?

>>> for x in d:
...     if d[x]==[]:
...             del d[x]
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
d = dict( [(k,v) for k,v in d.items() if len(v)>0])
Comments
Thank you very much!!!

Otherwise nice, but maybe v is not sequence.

Here is other form with del. You must iterate over d.keys() as dictionary changes during iteration:

d={'a':[],'b':['1','2'],'c':[], 'd':False, 'e':'', 'f': 0.0}
for k in d.keys():
    try:
        if len(d[k])<1:
            del d[k]
    except: pass
print d

ow... i was close to this but i dint use that try and except
there is another question for me.

If the dictionary is

d={'a':[('X','1),('X','2)],'b':[('Y','1)]

How can i make it to,

d={'a':{'X':['1','2']}, 'b':{'Y':['1']}}

ie., as a dictionary of dictionaries

Edited 6 Years Ago by knan: n/a

Just tell Python to make it dictionary:

d={'a':[('X','1'),('X','2')],'b':[('Y','1')]}

for key, item in d.items():
    d[key] = dict(item)
print d
            
""" Output:
{'a': {'X': '2'}, 'b': {'Y': '1'}}
"""

But because it has double keys, must do tricks:

d={'a':[('X','1'),('X','2')],'b':[('Y','1')]}

for key, item in d.items():
    d2 = {}
    for key2, item2 in item:
        d2[key2] = d2[key2]+ [item2] if key2 in d2 else [item2]
    d[key] = d2

print d
            
""" Output:
{'a': {'X': ['1', '2']}, 'b': {'Y': ['1']}}
"""

Edited 6 Years Ago by pyTony: n/a

This question has already been answered. Start a new discussion instead.