LearnFrenzy
Sign in Take a free test

List Comprehensions · List Comprehensions Coding Problems · Question 6

Parse CSV text into dictionaries with comprehensions in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Turn CSV text into a list of dicts with numeric marks, then list the students scoring above the class average.

Solution
main.py Run
csv_text = """name,marks
Asha,91
Ravi,64
Meera,85
Dev,58"""

header, *lines = csv_text.splitlines()
keys = header.split(",")
rows = [dict(zip(keys, line.split(","))) for line in lines]
rows = [{**r, "marks": int(r["marks"])} for r in rows]

avg = sum(r["marks"] for r in rows) / len(rows)
print(f"Average: {avg}")
print([r["name"] for r in rows if r["marks"] > avg])

Output Verified by running it on Python 3

Average: 74.5
['Asha', 'Meera']

zip pairs headers with values; a second comprehension rebuilds each dict with marks converted to int; a generator expression computes the average.

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