-1

I have a list of dictionaries and I want to do a for each to find corresponding values.

My list:

my_list = [{'genre':'Dystopia', 'book':'Hunger Games'},
           {'genre':'Fanstasy', 'book':'Harry Potter'},
           {'genre':'Dystopia', 'book':'Divergent'}]

I want to get books corresponding to the genre.

Expected result:

for 'Dystopia' get 'Hunger Games', 'Divergent'
for 'Fantasy' get 'Harry Potter'

I am not sure how to go about it. I know I need a for loop but don't know what to do beyond that.

for x in my_list:
   x['url']

Not sure what to add next.

nb_nb_nb
  • 1,243
  • 11
  • 36
  • What is the issue, exactly? That for loop looks fine to me. Why are you using a list of dictionaries for this? – AMC Jan 16 '20 at 17:03

6 Answers6

1

Try this.

[dictionary['book'] for dictionary in my_list if dictionary['genre'] == 'Dystopia']

This goes through all of the dictionaries in my_list and if the genre is Dystopia it records the book.

Below shows how to obtain a dictionary that contains all books for each genre.

genres = set([dictionary['genre'] for dictionary in my_list])
result = {genre:[dictionary['book'] for dictionary in my_list if dictionary['genre'] == genre] for genre in genres}
cmxu
  • 954
  • 5
  • 13
  • I have multiple genres and want to avoid hard coding values like Dystopia. I just wanted it to return the value for each of the genres – nb_nb_nb Jan 16 '20 at 15:08
0

you want to get a dictionary of genre -> list of books,

so you need to iterate my_list, take the genre (as the key) and the book (as the value) and append it to the list of books in this genre

using defaultdict will easily eliminate the corner case of the first book.

from collections import defaultdict

result = defaultdict(list)
for d in my_list:
  result[d['genre']].append(d['book'])
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
0

Hi please find the solution below.

my_list = [
{'genre':'Dystopia', 'book':'Hunger Games'},
           {'genre':'Fanstasy', 'book':'Harry Potter'},
           {'genre':'Dystopia', 'book':'Divergent'}
           ]
genre_holder = dict()
for item in my_list:
    if genre_holder.get(item['genre'],"empty") == "empty":
         genre_holder[item['genre']] = list()
    genre_holder[item['genre']].append(item['book'])
print(genre_holder)

for genre in genre_holder:
    print("for ",genre," get ", ",".join(genre_holder[genre]))
High-Octane
  • 1,104
  • 5
  • 19
0

For a more functional approach, this return a map of the correct books:

list(map(lambda x: x["book"], filter(lambda x: x["genre"] == "Dystopia", my_list)))
>>> ['Hunger Games', 'Divergent']
Johan Dettmar
  • 27,968
  • 5
  • 31
  • 28
0

You could do something like this:

books={}
for i in my_list:
    genre=i["genre"]
    book=i["book"]
    if genre in books:
        if book in books[genre]:
            continue
    else:
        books[genre]=[]
    books[genre].append(book)

print(books)

output

{'Dystopia': ['Hunger Games', 'Divergent'], 'Fanstasy': ['Harry Potter']}
Zaher88abd
  • 448
  • 7
  • 20
0

From this answer, you could try to create a new class from built-in dict:

class Dictlist(dict):
    def __setitem__(self, key, value):
        try:
            self[key]
        except KeyError:
            super(Dictlist, self).__setitem__(key, [])
        self[key].append(value)

So...

d = Dictlist()
for element in my_list:
    d[element['genre']] = d['book']

output:

{'Dystopia': ['Hunger Games', 'Divergent'], 'Fanstasy': ['Harry Potter']}
Gocht
  • 9,924
  • 3
  • 42
  • 81