LearnFrenzy
Sign in Take a free test

Lambda Functions · Lambda Functions Coding Problems · Question 8

Group records with itertools.groupby and a lambda in Python Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Group sales records by city with itertools.groupby (sorting first) and print each city's total.

Solution
main.py Run
from itertools import groupby

sales = [("Pune", 1200), ("Delhi", 800), ("Pune", 450), ("Kochi", 300), ("Delhi", 950)]
by_city = lambda s: s[0]

for city, rows in groupby(sorted(sales, key=by_city), key=by_city):
    amounts = [amount for _, amount in rows]
    print(f"{city:<6} {sum(amounts):>5} from {len(amounts)} sale(s)")

Output Verified by running it on Python 3

Delhi   1750 from 2 sale(s)
Kochi    300 from 1 sale(s)
Pune    1650 from 2 sale(s)

groupby only groups neighbouring items, so the data is sorted by the same key first.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links