Post

PythonPython

J
James ROBERT

Posted on 4th March 2024|17 views

0
votes

Python Csv To Dictionary

How to parse CSV formatted files using csv.DictReader?

Answers
P
Harish Harsh

Posted on 4th March 2024

Let us assume there is a data mans.csv

{'age': '10', 'height': '54', 'id': '1', 'weight': '120', 'name': 'raj'}

{'age': '30', 'height': '66', 'id': '2', 'weight': '120.6', 'name': 'jai'}

{'age': '15', 'height': '55', 'id': '3', 'weight': '110.0', 'name': 'veer'}

 

Now import CSV


 

import csv

input_file = csv.DictReader(open("mans.csv"))

maximum_age = None

oldest_man = None

for row in input_file:

    age = int(row["age"])

    if maximum_age == None or maximum_age < age:

        maximum_age = age

        oldest_man = row["name"]

 

if maximum_age != None:

    print "The oldest man is %s, who is %d % (oldest_man, maximum_age)

else:

    print "not there any man in the file"

 

Write your answer

STILL GOT QUERIES?

Get a Live FREE Demo
  • Explore the trending and niche courses and learning maps
  • Learn about tuition fee, payment plans, and scholarships
  • Get access to webinars and self-paced learning videos