如何遍历键名不同的Python字典并输出指定格式内容?
问题描述
给定如下Python字典:
prods = {'product_1': {'color': 'White', 'whls': '25.00', 'size_3': '0', 'size_4': '14', 'size_5': '35'}, 'product_2':{'color': 'Black', 'whls': '55.00', 'size_7': '10', 'size_7.5': '13', 'size_8': '35'}, 'product_3':{'color': 'Blue', 'whls': '65.00', 'size_6': '15', 'size_8': '11', 'size_10': '29'}}
需要遍历后输出如下格式:
White - size_3 - 0 White - size_4 - 14 White - size_5 - 35 Black - size_7 - 10 Black - size_7.5 -13 Black - size_8 - 35 Blue - size_6 - 15 Blue - size_8 - 11 Blue - size_10 - 29
用户熟悉键名统一的字典遍历逻辑,但不清楚如何处理键名不固定的size字段,当前代码卡在size键的处理环节:
for p in prods: for i in prods[p]: print(prods[p].get('color') + " - " + prods[p].get('size_') # This is where i get stuck, since all size keys are different
解决方案
核心思路是筛选出所有以size_开头的键,结合对应的color值完成输出,以下是两种可行实现:
方法一:基础遍历筛选
prods = {'product_1': {'color': 'White', 'whls': '25.00', 'size_3': '0', 'size_4': '14', 'size_5': '35'}, 'product_2':{'color': 'Black', 'whls': '55.00', 'size_7': '10', 'size_7.5': '13', 'size_8': '35'}, 'product_3':{'color': 'Blue', 'whls': '65.00', 'size_6': '15', 'size_8': '11', 'size_10': '29'}} for product in prods.values(): color = product['color'] # 遍历当前商品的键值对,仅处理size开头的键 for key, value in product.items(): if key.startswith('size_'): print(f"{color} - {key} - {value}") # 每个商品输出后添加空行 print()
方法二:紧凑写法(结合列表推导式)
如果追求代码简洁,可以先收集所有输出内容再统一打印:
prods = {'product_1': {'color': 'White', 'whls': '25.00', 'size_3': '0', 'size_4': '14', 'size_5': '35'}, 'product_2':{'color': 'Black', 'whls': '55.00', 'size_7': '10', 'size_7.5': '13', 'size_8': '35'}, 'product_3':{'color': 'Blue', 'whls': '65.00', 'size_6': '15', 'size_8': '11', 'size_10': '29'}} output_content = [] for product in prods.values(): color = product['color'] # 生成当前商品的所有size行 size_lines = [f"{color} - {k} - {v}" for k, v in product.items() if k.startswith('size_')] output_content.extend(size_lines) output_content.append('') # 商品间的分隔空行 # 打印所有内容 print('\n'.join(output_content))
关键说明
- 使用
prods.values()直接获取每个商品的字典对象,比遍历键再取值更直观高效。 - 通过
key.startswith('size_')精准筛选所有尺寸相关的键,不管后续数字格式如何都能匹配。 - 采用f-string进行字符串格式化,相比传统拼接更清晰、更易维护。
- 每个商品遍历结束后添加空行,严格匹配需求的输出格式。
内容的提问来源于stack exchange,提问作者djangonewbie123
相关产品推荐
相关产品推荐

