books = ['book1', 'book2', 'book3']
names = ['anas', 'jana', 'mo']
biglist = [{'anas' : {'book1' : 0, 'book2' : -2, 'book3' : 3}},
{'jana' : {'book1' : 5, 'book2' : 0, 'book3' : -3}},
{'mo' : {'book1' : 1, 'book2' : 5, 'book3' : 3}}]
I was planning to calculate the average for each book(excluding the zeros), so i came up with this list comprehension:
ratings={book:[biglist[i][names[j]][book] for i, _ in enumerate(biglist)] for book in books for j in range(len(names))}
sum_of_ratings = {book:sum(ratings[book]) for book in books}
avg_of_ratings = {book:sum_of_ratings[book]/len(ratings[book]) for book in books}
But when i run the code it gives this output:
ratings={book:[biglist[i][names[j]][book] for i, _ in enumerate(biglist)] for book in books for j in range(len(names))}
KeyError: 'anas'
Apparently, it doesn't find the keys even though is the same as the ones in the list.
NOTE : i'm not going to be using any built in functions in order to compute the average.
Your comprehension uses three different methods to iterate over a list; just use the simplest one!
You also forgot to exclude the zeroes from the average calculation (you'd need to take the len
of the list minus the zero elements). It's simpler to just use statistics.mean
and filter the zeroes out first.
You also don't even need the "user" keys since they aren't a part of this calculation, so doing lookups based on those adds more unnecessary complexity. Just take the values
of those dicts:
>>> ratings = {book: [d[book] for u in biglist for d in u.values()] for book in books}
>>> ratings
{'book1': [0, 5, 1], 'book2': [-2, 0, 5], 'book3': [3, -3, 3]}
>>> from statistics import mean
>>> avg_ratings = {book: mean(r for r in ratings[book] if r != 0) for book in books}
>>> avg_ratings
{'book1': 3, 'book2': 1.5, 'book3': 1}
Or you could just condense the whole thing into a single comprehension:
avg_ratings = {book: mean(
d[book] for u in biglist for d in u.values() if d[book] != 0
) for book in books}