Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return name of category with best average rating from list

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Structure of list:

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading