[英]Find average of certain values in dictionary for each key in dictionary
我有一個字典,它有一個字符串 id 作為鍵,一個列表列表作為值。 列表列表的第一個元素是圖書類型,第二個元素是圖書評級。 它看起來像這樣:
{'id1': [['Horror', 4.0], ['Sci-Fi', 9.5], ['Horror', 9.0]],
'id2': [['Thriller', 2.3], ['Horror', 6.2], ['Thriller', 3.9]]}
我想要做的是平均出每個 id 的每個流派的評級。 所以最后,我想要一本這樣的字典:
{'id1': [['Horror', 6.5], ['Sci-Fi', 9.5]],
'id2': [['Thriller', 3.1], ['Horror', 6.2]]}
我一直在嘗試做的是:
#existing_dictionary is the dictionary above
dict = {}
for bookAndRate in existing_dictionary.items():
for bookGenrePlusRating in bookAndRate[1]: #bookAndRate prints out [['Comedy', 4.0], ['Comedy', 4.9], ['Adventure', 7.8]]
#bookGenrePlusRating prints out ['Comedy', 4.0], then on a separate line, ['Comedy', 4.9], then on a separate line ['Adventure', 7.8]
if bookGenrePlusRating[0] in dict.values():
dict[id[0]][1] += bookGenrePlusRating[1]
else:
dict[id[0]] = [bookGenrePlusRating[0], bookGenrePlusRating[1]]
但這只是給了我每個 id 中的最后一個元素。 所以我最終得到
{'id1': ['Horror', 9.0],
'id2': ['Thriller', 3.9]}
嘗試:
from statistics import mean
dct = {
"id1": [["Horror", 4.0], ["Sci-Fi", 9.5], ["Horror", 9.0]],
"id2": [["Thriller", 2.3], ["Horror", 6.2], ["Thriller", 3.9]],
}
out = {}
for k, v in dct.items():
for genre, rating in v:
out.setdefault(k, {}).setdefault(genre, []).append(rating)
out = {k: [[kk, mean(vv)] for kk, vv in v.items()] for k, v in out.items()}
print(out)
印刷:
{
"id1": [["Horror", 6.5], ["Sci-Fi", 9.5]],
"id2": [["Thriller", 3.0999999999999996], ["Horror", 6.2]],
}
如果你想舍入花車:
out = {
k: [[kk, round(mean(vv), 2)] for kk, vv in v.items()]
for k, v in out.items()
}
print(out)
印刷:
{
"id1": [["Horror", 6.5], ["Sci-Fi", 9.5]],
"id2": [["Thriller", 3.1], ["Horror", 6.2]],
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.