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.
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"}
])
}
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'}]
If you are using Python 3, simply do:
list(filter(None, your_list_name))
This removes all empty dicts from your list.
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({})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With