Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete empty dict inside list of dictionary?

Tags:

python

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.

like image 369
drink-a-Beer Avatar asked Aug 24 '15 11:08

drink-a-Beer


4 Answers

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"}
        ])
}
like image 188
itzMEonTV Avatar answered Nov 13 '22 19:11

itzMEonTV


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'}]
like image 43
Christian Benke Avatar answered Nov 13 '22 17:11

Christian Benke


If you are using Python 3, simply do:

list(filter(None, your_list_name))

This removes all empty dicts from your list.

like image 26
CodeBiker Avatar answered Nov 13 '22 18:11

CodeBiker


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({})
like image 2
SuperBiasedMan Avatar answered Nov 13 '22 17:11

SuperBiasedMan