drink-a-Beer
drink-a-Beer

Reputation: 397

how to delete empty dict inside list of dictionary?

How can I remove empty dict from list of dict as,

{
 "ages":[{"age":25,"job":"teacher"},
         {},{},
         {"age":35,"job":"clerk"}
        ]
}

I am beginner to python. Thanks in advance.

Upvotes: 10

Views: 23574

Answers (6)

Sachin Sonigra
Sachin Sonigra

Reputation: 11

You can also try this

mylist = [{'age': 25, 'job': 'teacher'}, {}, {}, {'age': 35, 'job': 'clerk'}]

mylist=[i for i in mylist if i]

print(mylist)

Output:

[{'age': 25, 'job': 'teacher'}, {'age': 35, 'job': 'clerk'}]

Upvotes: 1

CodeBiker
CodeBiker

Reputation: 3263

If you are using Python 3, simply do:

list(filter(None, your_list_name))

This removes all empty dicts from your list.

Upvotes: 6

KumaTea
KumaTea

Reputation: 640

You may try the following function:

def trimmer(data):
    if type(data) is dict:
        new_data = {}
        for key in data:
            if data[key]:
                new_data[key] = trimmer(data[key])
        return new_data
    elif type(data) is list:
        new_data = []
        for index in range(len(data)):
            if data[index]:
                new_data.append(trimmer(data[index]))
        return new_data
    else:
        return data

This will trim

{
 "ages":[{"age":25,"job":"teacher"},
         {},{},
         {"age":35,"job":"clerk"}
        ]
}

and even

{'ages': [
    {'age': 25, 'job': 'teacher', 'empty_four': []},
    [], {},
    {'age': 35, 'job': 'clerk', 'empty_five': []}],
    'empty_one': [], 'empty_two': '',
    'empty_three': {}
}

to this: {'ages': [{'age': 25, 'job': 'teacher'}, {'age': 35, 'job': 'clerk'}]}

Upvotes: 1

Christian Benke
Christian Benke

Reputation: 497

There's a even simpler and more intuitive way than filter, and it works in Python 2 and Python 3:

You can do a "truth value testing" on a dict to test if it's empty or not:

>>> foo = {}
>>> if foo:
...   print(foo)
...
>>>
>>> bar = {'key':'value'}
>>> if bar:
...    print(bar)
...
{'key':'value'} 

Therefore you can iterate over mylist and test for empty dicts with an if-statement:

>>> mylist = [{'age': 25, 'job': 'teacher'}, {}, {}, {'age': 35, 'job': 'clerk'}]
>>> [i for i in mylist if i]
[{'age': 25, 'job': 'teacher'}, {'age': 35, 'job': 'clerk'}]

Upvotes: 5

SuperBiasedMan
SuperBiasedMan

Reputation: 9969

This while loop will keep looping while there's a {} in the list and remove each one until there's none left.

while {} in dictList:
    dictList.remove({})

Upvotes: 2

itzMEonTV
itzMEonTV

Reputation: 20369

Try this

In [50]: mydict = {
   ....:  "ages":[{"age":25,"job":"teacher"},
   ....:          {},{},
   ....:          {"age":35,"job":"clerk"}
   ....:         ]
   ....: }

In [51]: mydict = {"ages":[i for i in mydict["ages"] if i]}

In [52]: mydict
Out[52]: {'ages': [{'age': 25, 'job': 'teacher'}, {'age': 35, 'job': 'clerk'}]}

OR simply use filter

>>>mylist = [{'age': 25, 'job': 'teacher'}, {}, {}, {'age': 35, 'job': 'clerk'}]
>>>filter(None, mylist)
[{'age': 25, 'job': 'teacher'}, {'age': 35, 'job': 'clerk'}]

So in your dict, apply it as

{
 "ages":filter(None, [{"age":25,"job":"teacher"},
         {},{},
         {"age":35,"job":"clerk"}
        ])
}

Upvotes: 18

Related Questions