954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to remove empty keys in a dictionary

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

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

I want it to be

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


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
knan
Light Poster
29 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 
d = dict( [(k,v) for k,v in d.items() if len(v)>0])
cghtkh
Junior Poster
102 posts since Sep 2010
Reputation Points: 21
Solved Threads: 38
 

Thank you very much!

knan
Light Poster
29 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

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
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

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

knan
Light Poster
29 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

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']}}
"""
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Case solved?

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: