user3206440
user3206440

Reputation: 5049

python list of dicts remove items with empty lists

with a list l like below

l = [{'x': 2}, {'y': [], 'z': 'hello'}, {'a': []}]

need to eject the elements with an empty list as the value.

expected output

[{'x': 2}, {z: 'hello'}]

Was trying to achieve this with list comprehension, need help.

Upvotes: 1

Views: 149

Answers (5)

Kiran Subedi
Kiran Subedi

Reputation: 2284

You can try this one :

l = [{'x': 2}, {'y': [], 'z': 'hello'}, {'a': [],'b':'','c':0}]
print([ { k:v for k,v in ll.items() if v != [] } for ll in l ]);

Upvotes: 0

dawg
dawg

Reputation: 103694

An alternative is to: a) Use a simple loop to remove empty entries and b) filter the final list:

l = [{'x': 2}, {'y': [], 'z': 'hello'}, {'a': []}]

for i,d in enumerate(l):
    l[i]={k:v for k,v in d.items() if v!=[]}
l=list(filter(None, l))  

>>> l
[{'x': 2}, {'z': 'hello'}]

The advantage here (over a comprehension) is the list is edited in place vs copied.

Upvotes: 1

ELinda
ELinda

Reputation: 2821

Somewhat similar to existing responses, but uses a one-iteration list comprehension, with if to filter out the empty items.

def remove_empty(input_list):
    return [dict((k, v) for k, v in d.items() if v != [])
            for d in input_list
            if not (len(d) == 1 and list(d.values()) == [[]])]

remove_empty(l)

output:

[{'x': 2}, {'z': 'hello'}]

Upvotes: 0

Ch3steR
Ch3steR

Reputation: 20669

You can try this.

list(filter(None,({k:v for k,v in d.items() if v!=[]} for d in l)))
#[{'x': 2}, {'z': 'hello'}]

Upvotes: 3

user2390182
user2390182

Reputation: 73450

The following will work for your data:

>>> [d for d in ({k: v for k, v in d_.items() if v} for d_ in l) if d]
[{'x': 2}, {'z': 'hello'}]

The inner dict comprehension filters out those key-value pairs from the dicts with empty list values, the outer comprehension filters empty dicts.

Upvotes: 4

Related Questions