0
Follow
0
View

How to assign multiple variables to a dictionary [closed]

diotzhou 注册会员
2023-01-25 10:43

Firstly, when you said "I declared a list called books" you actually declared a dictionary.

Secondly, you had reassigned a file object to the namespace list_of_books and which should have given you an error when you tried to 'append' the dictionary object, but your code didn't even reach there, because instead of unpacking the element for that particular iteration you were trying to unpack the entire list_of_books object which gave you the "ValueError: Too many values to unpack".

Without changing any of your logic, to make this working the code should look like this:

 def retrieve_books():
    list_of_books = []

    with open("books.csv", "r") as books:
        for book in books:
            # Extracts the values from the CSV data
            title, author, year = book.split(",")

            # Creates a dictionary from the csv data and adds it to the books list
            list_of_books.append({
                "title": title,
                "author": author,
                "year": year
            })

    return list_of_books
duhaiyun2010 注册会员
2023-01-25 10:43

You're not actually parsing the csv line here. You need to use the csv module to properly parse a csv file.

import csv

def books():
    list_of_books = []
    with open('books.csv', 'r') as csvfile:
        csvreader = csv.reader(csvfile)
        for row in csvreader:
            list_of_books.append({
                'title': row[0] if 0
cxc02325 注册会员
2023-01-25 10:43

You have quite a lot of namespace collisions:

def books():
    list_of_books = {}

At this point list_of_books is an empty dictionary.

with open("books.csv", "r") as list_of_books:
    for books in list_of_books:
        # Extracts the values from the CSV data

At this point list_of_books is a file object, which you iterate linewise.

title, author, year = list_of_books

This unpacks the whole file into three variables. Unless you have three lines it will fail, but in any case what you want is:

title, author, year = books

Note this will still fail if there are more than 3 entries in books. Presumably you do something to books first (like splitting it by ",", as in the code presented it's just a string, so this will fail (it will try to unpack the string by character, so if it more than 3 chars long it will bail).

list_of_books.append({
                      "title": title,
                       "author": author,
                       "year": year})

Now we're appending to the file object. If your code got this far it would fail with AttributeError. You need to call your list_of_books something different. But you also want it to be a list:

results = []
results.append(...)

The same goes for the end, where you return list_of_books, which is still a file object.

The moral is: name your list_of_books something else, or name your file object (as ...) something else, and declare your list as a list.

duesuda 注册会员
2023-01-25 10:43

Given that you wanted a list consisting of each book detail in the form of a dictionary, you could get every value inside the record using books.split(","). Your code defined list_of_books as a list and then proceeded to use it as a file object which raised an Attribute Error which is why the dictionary could not be appended.
This code uses a separate variable bookList to append each record from the csv file and return the final output.

def retrieve_books():
    bookList = []
    with open("books.csv", "r") as list_of_books:
        for books in list_of_books:
            # Extracts the values from the CSV data
            title, author, year = books.split(",")
            # Creates a dictionary from the csv data and adds it to the books list
            book = {
                "title": title,
                "author": author,
                "year": year
            }
            
            bookList.append(book)

    return bookList

About the Author

Question Info

Publish Time
2023-01-25 10:43
Update Time
2023-01-25 10:43