如何将Python中存储标签分类的嵌套字典格式化为指定结构的表格
解决方案
实现分为两步:首先反转原始字典的结构,整理出每个物品对应的各分类标签;再按自定义列宽统一输出表头、分隔线和数据行。
完整可运行代码如下(已包含示例测试数据,可直接替换为你自己生成的分类字典):
# 示例分类字典,可替换为你程序生成的结果 rockdictionary = { 'colors': { 'red': ['thing1', 'thing 4'], 'blue': ['thing 2', 'thing 3'], 'yellow':['thing 5'] }, 'texture': { 'smooth': ['thing 5', 'thing 3'], 'rough': ['thing1'], 'bumpy':['thing4', 'thing 2'] }, 'size': { 'small': ['thing 2', 'thing 4', 'thing 3'] , 'medium': [], 'large':['thing 1', 'thing 5'] } } # 1. 预处理:生成物品-标签映射表 item_tag_dict = {} categories = list(rockdictionary.keys()) all_items = set() # 遍历原始字典收集所有物品和对应标签 for cate_name, sub_cate_map in rockdictionary.items(): for sub_cate, item_list in sub_cate_map.items(): for item in item_list: all_items.add(item) if item not in item_tag_dict: item_tag_dict[item] = {c: '' for c in categories} item_tag_dict[item][cate_name] = sub_cate # 2. 获取用户输入的列宽 user_width = int(input('How wide would you like your columns to be? ')) # 3. 输出表头 header_list = ['item'] + categories for idx, header in enumerate(header_list): end_char = '|' if idx != len(header_list)-1 else '\n' print(f'{header:>{user_width}}', end=end_char) # 输出表头分隔线 total_width = user_width * len(header_list) + (len(header_list) - 1) print('-' * total_width) # 4. 输出每行数据 for item in item_tag_dict: row_data = [item] + [item_tag_dict[item][cate] for cate in categories] for idx, val in enumerate(row_data): end_char = '|' if idx != len(row_data)-1 else '\n' print(f'{val:>{user_width}}', end=end_char)
实现说明
- 自动收集所有物品名称,不需要手动维护物品列表
- 表头和数据行使用相同的格式化逻辑,保证列对齐
- 分隔线长度自动适配列数和自定义列宽,不需要手动计算长度
内容的提问来源于stack exchange,提问作者Amabilia
相关产品推荐
相关产品推荐

