Home > Enterprise >  Extracting data as python dict from CSV file
Extracting data as python dict from CSV file

Time:12-07

how do i extract the data is this CSV as a python dictionary without importing packages? sample of the data:

User-ID;"ISBN";"Book-Rating" 276725;"034545104X";"0" 276726;"0155061224";"5" 276727;"0446520802";"0" 276729;"052165615X";"3"

def loadRatings():
  # Get bookratings
    try:
        bookR = {}
        for line in open('booktext.csv'):
            (id,title) = line.split(';')[0:2]
            bookR[id] = title
        return bookR
    except IOError as ioerr:
        print('File error: '   str(ioerr))
        
print(loadRatings())

but i need my result to be like

bookR = {User-ID: 276725, ISBN: 034545104X, Rating: 0}

CodePudding user response:

import csv

filename ="Geeks.csv"

opening the file using "with"

statement

with open(filename, 'r') as data: for line in csv.DictReader(data): print(line)

CodePudding user response:

this code will return

with open("booktext.csv") as f:
    for i, line in enumerate(f):
        # skip header
        if i == 0:
            continue
        row_lst = line.replace("\n","").replace('"','').split(";")
        if len(row_lst) == 3:
            bookR = {
                "User-ID": row_lst[0],
                "ISBN": row_lst[1],
                "Rating": row_lst[2]
            }
            print(bookR)

{'User-ID': '276725', 'ISBN': '034545104X', 'Rating': '0'}

{'User-ID': '276726', 'ISBN': '0155061224', 'Rating': '5'}

{'User-ID': '276727', 'ISBN': '0446520802', 'Rating': '0'}

{'User-ID': '276729', 'ISBN': '052165615X', 'Rating': '3'}

You always should use context manager with when working with files unless you really know and have a good reason why not to do that. Read more on that on https://stackoverflow.com/a/3012921/20646982

  • Related