Python嵌套字典打印优化:调整属性顺序、添加间隔及分页输出
Python 新手:调整图书集合打印格式的需求
我是Python新手,现在有一个包含图书信息的嵌套字典,里面有两本图书,每本有8个属性:
book_collection ={ 17104: {'Title': 'A River', 'Author': 'Elisha Mitchell', 'Publisher': 'FPG Publishing', 'Pages': '345', 'Year': '2014', 'Copies': 2, 'Available': 2, 'ID': 17104}, 37115: {'Title': 'Aim High', 'Author': 'George Tayloe Winston', 'Publisher': 'Manning Hall Press', 'Pages': '663', 'Year': '2014', 'Copies': 5, 'Available': 5, 'ID': 37115} } # 当前使用的代码 for id, book in book_collection.items(): for book_attribute, attribute_value in book.items(): print(book_attribute, ': ', attribute_value, sep='')
当前输出是:
Title: A River Author: Elisha Mitchell Publisher: FPG Publishing Pages: 345 Year: 2014 Copies: 2 Available: 2 ID: 17104 Title: Aim High Author: George Tayloe Winston Publisher: Manning Hall Press Pages: 663 Year: 2014 Copies: 5 Available: 5 ID: 37115
我需要实现三个需求:
- 将每本图书的ID属性打印在第一行;
- 图书之间添加空行分隔;
- 当图书总数为20本时,先打印前10本,再询问用户是否继续打印剩余内容。
解决方案
下面是满足所有需求的代码,关键逻辑已标注注释:
book_collection ={ 17104: {'Title': 'A River', 'Author': 'Elisha Mitchell', 'Publisher': 'FPG Publishing', 'Pages': '345', 'Year': '2014', 'Copies': 2, 'Available': 2, 'ID': 17104}, 37115: {'Title': 'Aim High', 'Author': 'George Tayloe Winston', 'Publisher': 'Manning Hall Press', 'Pages': '663', 'Year': '2014', 'Copies': 5, 'Available': 5, 'ID': 37115} } # 将字典转为列表,方便按数量分割处理 books_list = list(book_collection.values()) total_books = len(books_list) # 每批次打印的图书数量 batch_size = 10 # 分批次遍历图书 for i in range(0, total_books, batch_size): current_batch = books_list[i:i+batch_size] for idx, book in enumerate(current_batch): # 优先打印ID属性 print(f'ID: {book["ID"]}') # 遍历剩余属性,跳过已打印的ID for attr, value in book.items(): if attr != 'ID': print(f'{attr}: {value}') # 图书间添加空行,避免最后一本后出现多余空行 if idx != len(current_batch) - 1 or (i + idx + 1) != total_books: print() # 非最后一批时,询问用户是否继续打印 if i + batch_size < total_books: user_choice = input("是否继续打印剩余图书?(y/n): ").strip().lower() if user_choice != 'y': break
逻辑说明:
- ID前置打印:每遍历一本图书时,先单独输出
ID,再遍历其他属性并跳过ID字段,确保ID始终在第一行。 - 图书间空行:通过判断当前图书是否为批次内最后一本、且不是所有图书的最后一本,来添加空行分隔,避免结尾出现多余空行。
- 分批次询问:将图书字典转为列表后,按10本为一批次分割,每打印完一批(非最后一批)就询问用户,输入非
y则终止打印流程。
如果测试20本图书的场景,只需给book_collection补充足够的图书条目,代码会自动处理分批次逻辑。
内容的提问来源于stack exchange,提问作者Theo
相关产品推荐
相关产品推荐

