At Acme Analytics, raw sales events are represented as Python dictionaries. Write a function that groups valid records by category, sums revenue per category, and returns the top k categories.
A record is valid only if it contains the keys category, price, and quantity, where category is a non-empty string and both price and quantity are non-negative numbers. Revenue for one record is price * quantity. If multiple valid records share the same category, their revenues should be added together. Return the result as a list of [category, total_revenue] pairs sorted by descending total revenue; if two categories have the same revenue, sort them by ascending category name. Return only the first k pairs. If k is larger than the number of categories, return all categories.
records is a list of dictionaries, k is an integer[category, total_revenue] pairsExample 1
records = [{"category":"books","price":10,"quantity":2},{"category":"games","price":20,"quantity":1},{"category":"books","price":5,"quantity":4}], k = 2[["books", 40], ["games", 20]]books = 10*2 + 5*4 = 40, games = 20*1 = 20.Example 2
records = [{"category":"tech","price":100,"quantity":1},{"category":"","price":50,"quantity":2},{"category":"tech","price":30,"quantity":2}], k = 3[["tech", 160]]1 <= len(records) <= 10^40 <= price, quantity <= 10^61 <= k <= 10^4records = [{"category":"books","price":10,"quantity":2},{"category":"games","price":20,"quantity":1},{"category":"books","price":5,"quantity":4}], k = 2Output[["books", 40], ["games", 20]]WhyThe two `books` records are combined into one total of 40, which is larger than `games` at 20.records = [{"category":"tech","price":100,"quantity":1},{"category":"","price":50,"quantity":2},{"category":"tech","price":30,"quantity":2}], k = 3Output[["tech", 160]]WhyThe record with an empty category is invalid, so only the two valid `tech` records are counted.records = [{"category":"a","price":5,"quantity":2},{"category":"b","price":10,"quantity":1}], k = 1Output[["a", 10]]WhyBoth categories have revenue 10, so the tie is broken by category name and `a` comes first.1 <= len(records) <= 10^4Each record is a Python dictionary0 <= price, quantity <= 10^6 for valid records1 <= k <= 10^4Ignore records missing required keys or containing invalid valuesdef top_category_revenue(records, k):