Jom
Jom

Reputation: 25

Python: Filter Empty Strings From Multiple List of Dictionaries

May I know how can I come up with my expected result. I'm struggling this for an hour using “if” statement but nothing happened.

books = [{'title':'Angels and Demons'},{'title':''},{'title':'If'},{'title':'Eden'}]
authors = [{'author':'Dan Brown'},{'author':'Veronica Roth'},{'author':''},{'author':'James Rollins'}]

for i, book in enumerate(books):
    print(book, authors[i])

expected result:
({'title': 'Angels and Demons'}, {'author': 'Dan Brown'})
({'title': 'Eden'}, {'author': 'James Rollins'})

Upvotes: 0

Views: 89

Answers (4)

Anurag Misra
Anurag Misra

Reputation: 1544

One line code for your problem

In [3]: [(book, author) for book, author in zip(books,authors) if book['title'] and author['author']]
Out[3]: 
[({'title': 'Angels and Demons'}, {'author': 'Dan Brown'}),
 ({'title': 'Eden'}, {'author': 'James Rollins'})]

Upvotes: 1

stamaimer
stamaimer

Reputation: 6475

What you want might be exclude the pair which the title or the author is empty string.

books = [{'title':'Angels and Demons'},{'title':''},{'title':'If'},{'title':'Eden'}]
authors = [{'author':'Dan Brown'},{'author':'Veronica Roth'},{'author':''},{'author':'James Rollins'}]

for book, author in zip(books, authors):
    if book["title"] and author["author"]:
        print(book, author)

# or 

[(book, author) for book, author in zip(books, authors) if book["title"] and author["author"]]

Upvotes: 2

Kallz
Kallz

Reputation: 3523

Using List Comphersion

 [(books[i],authors[i]) for i,v in enumerate(books) if books[i]['title']  and authors[i]['author']]

Output:

 [({'title': 'Angels and Demons'}, {'author': 'Dan Brown'}), ({'title': 'Eden'}, {'author': 'James Rollins'})]

Upvotes: 1

Max
Max

Reputation: 1363

books = [{'title':'Angels and Demons'},{'title':''},{'title':'If'},{'title':'Eden'}]
authors = [{'author':'Dan Brown'},{'author':'Veronica Roth'},{'author':''},{'author':'James Rollins'}]

for i, book in enumerate(books):
    if book['title'] != '':
        print(book, authors[i])

This should work

Upvotes: -1

Related Questions