如何遍历嵌套字典?优化披萨订单收据风格输出格式
嵌套字典遍历与收据式输出优化方案
一、如何遍历嵌套字典
遍历嵌套字典最常用的方式是嵌套循环,针对两层嵌套的披萨订单字典,外层循环遍历披萨条目,内层循环遍历对应披萨的配料:
# 遍历两层嵌套字典的示例 for pizza_name, toppings in toppings_dict.items(): print(f"披萨:{pizza_name}") # 缩进显示配料 for topping_key, topping_value in toppings.items(): print(f" {topping_key}: {topping_value}")
如果字典嵌套深度不确定,可使用递归遍历适配任意层级:
def traverse_nested_dict(nested_dict, indent=0): for key, value in nested_dict.items(): print(" " * indent + f"{key}:") if isinstance(value, dict): traverse_nested_dict(value, indent + 1) else: print(" " * (indent + 1) + str(value))
二、优化代码输出为收据格式
针对你提供的代码,我们调整输出逻辑,实现配料缩进、分隔线、精简符号的收据样式:
优化后的完整代码
def topping_type_and_num(amount_of_toppings, count, toppings_dict): toppings_chosen = {} for a in range(int(amount_of_toppings)): list_of_toppings() # 假设此函数用于展示可选配料列表 topping_chosen = input("\n请选择配料:") # 用更直观的键名替代topping_1格式 toppings_chosen[f"配料{a+1}"] = topping_chosen # 更新嵌套字典,绑定当前披萨条目 toppings_dict[f"Pizza_{count}"] = toppings_chosen # 输出优化后的收据格式 print("\n=== 披萨订单收据 ===") for pizza_name, toppings in toppings_dict.items(): print(pizza_name) # 缩进显示每个配料,去掉多余符号 for topping_label, topping in toppings.items(): print(f" {topping_label}: {topping}") # 披萨条目间添加分隔线 print("-" * 35)
优化说明
- 缩进显示配料:通过在配料前添加两个空格,实现层级区分,符合收据排版习惯
- 精简符号:去掉原输出中的引号、冗余逗号,用
配料X: 名称的简洁格式展示 - 分隔线区分条目:每个披萨条目后添加35个短横线,清晰分隔不同订单
- 直观键名:将
topping_1改为配料1,更符合中文阅读习惯(若需保留原格式可改回topping_{a+1})
示例输出效果
=== 披萨订单收据 === Pizza_0 配料1: 芝士 配料2: 火腿 配料3: 蘑菇 ----------------------------------- Pizza_1 配料1: 橄榄 配料2: 青椒 -----------------------------------
内容的提问来源于stack exchange,提问作者Calen
相关产品推荐
相关产品推荐

