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

Recommended Answers

All 6 Replies

d = dict( [(k,v) for k,v in d.items() if len(v)>0])
commented: Thank you very much!!! +1

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

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']}}
"""

Case solved?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.