无法访问字典中的键

Can't access keys in the dict

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}}]

我打算计算每本书的平均值(不包括零),所以我想到了这个列表理解:

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}

但是当我 运行 代码时,它给出了这个输出:

ratings={book:[biglist[i][names[j]][book] for i, _ in enumerate(biglist)] for book in books for j in range(len(names))}
KeyError: 'anas'

显然,即使与列表中的键相同,它也找不到键。

NOTE : i'm not going to be using any built in functions in order to compute the average.

您的理解使用三种不同的方法来迭代列表;就用最简单的吧!

您还忘记从平均计算中排除零(您需要将列表的 len 减去零元素)。只使用 statistics.mean 并先过滤掉零会更简单。

您甚至不需要 "user" 键,因为它们不是此计算的一部分,因此基于这些进行查找会增加更多不必要的复杂性。只需使用这些命令的 values

>>> 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}

或者你可以将整个事情浓缩成一个单一的理解:

avg_ratings = {book: mean(
    d[book] for u in biglist for d in u.values() if d[book] != 0
) for book in books}