8

If I have a dictionary, and I want to remove the entries in which the value is an empty list [] how would I go about doing that?

I tried:

for x in dict2.keys():
    if dict2[x] == []:
        dict2.keys().remove(x)

but that didn't work.

8 Answers 8

14

Newer versions of python support dict comprehensions:

dic = {i:j for i,j in dic.items() if j != []}

These are much more readable than filter or for loops

Sign up to request clarification or add additional context in comments.

Comments

12

.keys() provides access to the list of keys in the dictionary, but changes to it are not (necessarily) reflected in the dictionary. You need to use del dictionary[key] or dictionary.pop(key) to remove it.

Because of the behaviour in some version of Python, you need to create a of copy of the list of your keys for things to work right. So your code would work if written as:

for x in list(dict2.keys()):
    if dict2[x] == []:
        del dict2[x]

3 Comments

Does not work, because you cannot change the size of a dictionary during iteration.
Corrected for Python 2.5/2.6/2.7/3.1.
In Python 3 it behaves differently, and gets angry if you modify the dict while iterating over .keys(). (Python 2 automatically creates a list, I believe.)
3
for x in dict2.keys():
    if dict2[x] == []:
        del dict2[x]

2 Comments

Using .keys() creates a new list to iterate, allowing you to delete from the original. Good Work
It does not do so in Python 3, and this will raise RuntimeError: dictionary changed size during iteration.
3

Why not just keep those which are not empty and let the gc to delete leftovers? I mean:

dict2 = dict( [ (k,v) for (k,v) in dict2.items() if v] )

Comments

1
for key in [ k for (k,v) in dict2.items() if not v ]:
  del dict2[key]

Comments

1

Clean one, but it will create copy of that dict:

dict(filter(lambda x: x[1] != [], d.iteritems()))

Comments

1

With generator object instead of list:

a = {'1': [], 'f':[1,2,3]}
dict((data for data in a.iteritems() if data[1]))

Comments

1
def dict_without_empty_values(d):
    return {k:v for k,v in d.iteritems() if v}


# Ex;
dict1 = {
    'Q': 1,
    'P': 0,
    'S': None,
    'R': 0,
    'T': '',
    'W': [],
    'V': {},
    'Y': None,
    'X': None,
}

print dict1
# {'Q': 1, 'P': 0, 'S': None, 'R': 0, 'T': '', 'W': [], 'V': {}, 'Y': None, 'X': None}

print dict_without_empty_values(dict1)
# {'Q': 1}

1 Comment

how can we do this is in python2.6?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.