Home > OS >  Return name of category with best average rating from list
Return name of category with best average rating from list

Time:10-26

I have list of products and I need to calculate average rating for every category based on it's products rating. The problem is that I don't know exactly number of categories and products in each category.

So basically there is n categories and m products in it and need to calculate average rating of every category and return name of the one with best average rating.

Desire Output : The best category is "phone" with average rating of "910"

Structure of list:

"products": [
    {
      "category": "pc",
      "rating": 1000,
    },
    {
      "category": "pc",
      "rating": 800,
    },
    {
      "category": "phone",
      "rating": 860,
    },
    {
      "category": "phone",
      "rating": 960,
    },
]

CodePudding user response:

Try:

data = {
    "products": [
        {
            "category": "pc",
            "rating": 1000,
        },
        {
            "category": "pc",
            "rating": 800,
        },
        {
            "category": "phone",
            "rating": 860,
        },
        {
            "category": "phone",
            "rating": 960,
        },
    ]
}

from statistics import mean

tmp = {}
for p in data["products"]:
    tmp.setdefault(p["category"], []).append(p["rating"])

tmp = {k: mean(v) for k, v in tmp.items()}

for k, v in tmp.items():
    print("Category:", k)
    print("Average:", v)
    print()

best = max(tmp, key=tmp.get)
print(f"Best average: {best} Average: {tmp[best]}")

Prints:

Category: pc
Average: 900

Category: phone
Average: 910

Best average: phone Average: 910
  • Related