首页 文章

如何从数据库中返回字典?

提问于
浏览
-2

我编写了访问数据库的函数 .

名为 Books 的表具有:

- a `book_id` TEXT column, 
- a title TEXT column, and 
- an author TEXT column.

对于第一个, run_query 是连接数据库的函数 .

get_book_cnt_per_author 是一个以这种形式返回元组列表的函数:

'author', number of books

我不知道如何通过循环使用 run_query 函数 . 因为我写的东西,我总是得到 None .

我不知道我的问题在哪里 . 我只为每位作者收到一本书 .

请告诉我这是什么问题 .

def get_books(db,book_cnt_list,book_cnt):“”“(str,tuple列表,int) - > str列表

Precondition: the elements in book_cnt_list are sorted
in ascending order by author name. 

Return a list of all the book titles whose authors
each have book_cnt books in the database with name db
according to the book_cnt_list. The book titles should be in 
ascending order for each author, but not for the entire list. 
Follow ascending order across authors, that is, the order
authors appear in book_cnt_list that is already sorted by 
author name. 

>>> author_cnt_list = get_book_cnt_per_author("e7_database.db")
>>> books_list = get_books("e7_database.db", author_cnt_list, 10) 
>>> books_list[0]
'A Christmas Carol'
>>> books_list[9]
'The Life and Adventures of Nicholas Nickleby'
>>> books_list[10]
'Disgrace'
>>> books_list[-1]
'Youth'
""" 

# HINT: First figure out which authors have book_cnt books
# using the book_cnt_list.  Then, access the database db
# to retrieve the required information for those authors.

# Do not call any other of your E7 functions other than run_query.
list1 = []
for i in book_cnt_list:
    if i[1] == "book_cnt":
        list1.append(i[0])
for j in list1:
    return run_query(my_db, '''SELECT title FROM Books OREDER BY Books.title ASC WHERE Books.author = ? ''', (j))

def create_author_dict(db):“”“(str) - > {str:list of str}的字典

Return a dictionary that maps each author to the books they have written
according to the information in the Books table of the database
with name db. 

>>> author_dict = create_author_dict('e7_database.db')
>>> author_dict['Isaac Asimov'].sort()
>>> author_dict['Isaac Asimov']
['Foundation', 'I Robot']
>>> author_dict['Maya Angelou']
['I Know Why the Caged Bird Sings']
"""  
con = sqlite3.connect(db)
cur = con.cursor()

cur.execute('''SELECT author, title FROM Books WHERE Books.author = ?''')
new_list = cur.fetchall()
new_dict = {}
for i in new_list:
    key = i[0]
    value = i[1:]
    new_dict.update({key: list(value)})

con.commit()
cur.close()
con.close()

return new_dict

1 回答

  • 0

    尝试改变:

    new_dict.update({key: list(value)})
    

    对于如下声明:

    new_dict[key] = new_dict.get(key, list()) + [value]
    

相关问题