java数据库字典用法_如何从数据库中返回字典?

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

名为 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值