List comprehension on nested lists with condition

Viewed 44

I have a list

list1 = [ [2,3,4] ,[5,6,7] ,[1,5,8] ,[2,3,{'key1':12}] ]

From list1 I need to remove the list which has a dictionary element and generate list2 which should be [ [2,3,4] ,[5,6,7] ,[1,5,8] ]

with a for loop I can get the list2 like

for e1 in list1:
    condition = 0
    for e2 in e1:
        if type(e2) is dict:
            condition = 1
    if not condition:
        list2.append(e1)

How can I get the result for list2 with list comprehension?

1 Answers

Try:

list1 = [[2, 3, 4], [5, 6, 7], [1, 5, 8], [2, 3, {"key1": 12}]]

list2 = [l for l in list1 if dict not in map(type, l)]
print(list2)

Prints:

[[2, 3, 4], [5, 6, 7], [1, 5, 8]]

Or using any() (Thanks @chepner):

list2 = [l for l in list1 if not any(isinstance(x, dict) for x in l)]
print(list2)
Related