0

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}

3 Answers3

0

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

0

The description is vague in terms of what you are looking for, not clear either it should be a single dict of all items, or just a separate lines. In case you need a normal dict you can use this simple approach with just few formatting later depends on data type you are requiring. I managed to recreate results like this:

with open('ex.csv',newline="") as f:
    d = list(f.read().split(' '))
    keys = d[0].split(';')
    values = d[1:]
    book = {}
    for idx, key in enumerate(keys):
        book[key] = []
        for i in range(len(values)):
            book[key].append(values[i].split(';')[idx])

Which produces results:

{'User-ID': ['276725', '276726', '276727', '276729'],
'"ISBN"': ['"034545104X"', '"0155061224"', '"0446520802"', '"052165615X"'],
'"Book-Rating"': ['"0"', '"5"', '"0"', '"3"']}
statlad
  • 128
  • 11
-1
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)
Paul Brennan
  • 2,638
  • 4
  • 19
  • 26