def find_details(id2find):
    surfers_f = open("surfing_data.csv")
    
    for eash_line in surfers_f:
        s = {}
        
        (s["id"], s["country"], s["average"], s["board"], s["age"]) = eash_line.split(";")
        
        if id2find == int(s["id"]):
            surfers_f.close()
            
            return(s)
        return({})
    
lookup_id = int(input("Enter the id of the surfer: "))

surfer = find_details(lookup_id)

if surfer:
    print("ID:         " + surfer["id"])
    print("Name:       " + surfer["name"])
    print("Country:    " + surfer["Average"])
    print("Board type: " + surfer["board"])
    print("Age:        " + surfer["age"])

The database file can be found at http://www.headfirstlabs.com/books/hfprog/

In the above program I'M getting two errors, one on line 7 and another on line 17. I can't figure out what's going on. It says to many values to unpack. Thanks for any and all help.

One more thing, what is a .csv file

Dani AI

Generated

Three distinct issues explain the errors in the thread: a mismatch between the number of fields produced by splitting a CSV line and the number of variables on the left (the ValueError), an early return inside the loop (so the file is checked only once), and key/case mismatches when printing the dictionary. and already spotted the missing name field and the indentation/return problem; the pragmatic fix is to parse the file reliably and only assign to the dictionary when a row has the expected number of fields.

A robust, minimal approach is to use Python's csv module and detect the delimiter, skip a header if present, and only accept rows with the expected column count. Example:

import csv

def find_details(id2find, path='surfing_data.csv'):
    cols = ['id','name','country','average','board','age']
    with open(path, newline='', encoding='utf-8') as f:
        sample = f.read(4096); f.seek(0)
        sniffer = csv.Sniffer()
        try:
            dialect = sniffer.sniff(sample, delimiters=',;|\t')
            has_header = sniffer.has_header(sample)
        except csv.Error:
            dialect = csv.excel; dialect.delimiter = ';'; has_header = False
        reader = csv.reader(f, dialect)
        if has_header:
            next(reader, None)
        for row in reader:
            if len(row) != len(cols):
                continue
            row = [c.strip() for c in row]
            try:
                if int(row[0]) == int(id2find):
                    return dict(zip(cols, row))
            except ValueError:
                continue
    return {}

Troubleshooting tips: print repr(line) and len(line.split(...)) on the offending line to see its actual fields; watch for quoted fields that contain delimiters; avoid searching by substring (as suggested) because "12" would match "112". When printing, use matching dictionary keys and prefer print("ID:", surfer["id"]) or convert values with str() rather than concatenating without conversion.

Summary: detect delimiter with csv.Sniffer, move the return outside the loop so all rows are checked, validate row length before unpacking, and keep key names and case consistent.

Recommended Answers

All 5 Replies

def find_details(id2find):
    surfers_f = open("surfing_data.csv")
    
    for eash_line in surfers_f:
        s = {}
        
        (s["id"], s["name"],s["country"], s["average"], s["board"], s["age"]) = eash_line.split(";") ## name field
        
        if id2find == int(s["id"]):
            surfers_f.close()
            
            return(s)
        return({})
    
lookup_id = int(input("Enter the id of the surfer: "))

surfer = find_details(lookup_id)

if surfer:
    print("ID:         " + surfer["id"])
    print("Name:       " + surfer["name"])
    print("Country:    " + surfer["average"]) ## small a
    print("Board type: " + surfer["board"])
    print("Age:        " + surfer["age"])

csv = comma separated values file is file with separator between field (comma), typically comma,semicolon,tab,space. It has many variations: sometimes fields are quoted sometimes not etc.

There are a couple of obvious mistakes in the original code, tony pointed some of those out already:

Looks like there are 6 items to extract in each line, s["name"] is missing

Python indentations are important, return({}) needs to line up with the for, or it will return an empty dictionary after just one iteration.

Python is case sensitive, so surfer["Average"] has to be surfer{"average"]

Note:
Comma Separated Values (CSV) files are generated by most common spreadsheet programs. In this case the comma has been replaced by a semicolon.

Also to make your app a bit more efficient first search for the id in the file then assign them to the dictionary, some thing like this.

if str(id2find) in each_line:
   #assign values to dictionary
   #close file
   #return dict
else:
   return s

csv = comma separated values file is file with separator between field (comma), typically comma,semicolon,tab,space. It has many variations: sometimes fields are quoted sometimes not et

def find_details(id2find):
    surfers_f = open("surfing_data.csv")
    
    for eash_line in surfers_f:
        s = {}
        
        (s["id"], s["name"],s["country"], s["average"], s["board"], s["age"]) = eash_line.split(";") ## name field
        
        if id2find == int(s["id"]):
            surfers_f.close()
            
            return(s)
        return({})
    
lookup_id = int(input("Enter the id of the surfer: "))

surfer = find_details(lookup_id)

if surfer:
    print("ID:         " + surfer["id"])
    print("Name:       " + surfer["name"])
    print("Country:    " + surfer["average"]) ## small a
    print("Board type: " + surfer["board"])
    print("Age:        " + surfer["age"])

csv = comma separated values file is file with separator between field (comma), typically comma,semicolon,tab,space. It has many variations: sometimes fields are quoted sometimes not etc.

csv = comma separated values file is file with separator between field (comma), typically comma,semicolon,tab,space. It has many variations: sometimes fields are quoted sometimes not etv

I mean these lines from three different csv files, for example:

abdc,safa,dadfa,afsdaf,asdfaj,asdfads

adsfa;asfaf;dafsdaf;dfa

"asfdfja","dfasdöf","faösfa","dfasöd"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.