Home » excel » Excel parsing in python and forming dictionary

Excel parsing in python and forming dictionary

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have an Excel file with a lot of data in it . i would like to get the info like in a dictionary example the first column of the excel will be the key and the rest of the column will be the values

Excel:
No name lastname hobby
1  jhon g        fishing
2  mike a        boxing
3  tom  v        sking

is it possible to have it like

dict = {No:1, name:jhon, lastname:g, hobby:fishing},
dict = {No:2, name:mike, lastname:a, hobby:boxing},

i tried converting the excel to csv and tried csv.DictReader it did not work for me is there any other way

How to&Answers:

Given the following CSV file:

No,name,lastname,hobby
1,jhon,g,fishing
2,mike,a,boxing
3,tom,v,sking

The following code appears to do what you’re asking for:

In [1]: import csv

In [2]: for d in csv.DictReader(open('file.txt')): print d
   ...: 
{'hobby': 'fishing', 'lastname': 'g', 'name': 'jhon', 'No': '1'}
{'hobby': 'boxing', 'lastname': 'a', 'name': 'mike', 'No': '2'}
{'hobby': 'sking', 'lastname': 'v', 'name': 'tom', 'No': '3'}