Python:如何比较同键字典值判断预算收支?是否需编写函数?
解决方案
首先,两个字典的键一一对应,我们可以遍历每个名字,对比total_per_person中的总花费和name_to_budget中的预算,判断每个人的收支状态。
基础实现(无需函数)
直接通过循环遍历所有名字,逐个比较并输出结果:
total_per_person = {'Edith': 79.24, 'Carol': 176.05, 'Hannah': 90.45, 'Frank': 66.6, 'Alice': 64.10, 'Ingrid': 59.45, 'Bob': 103.50, 'Gertrude': 107.45, 'Dave': 62.24} name_to_budget = {'Alice': 62.12, 'Bob': 40.34, 'Carol': 46.69, 'Dave': 37.79, 'Edith': 95.39, 'Frank': 32.87, 'Gertrude': 29.13, 'Hannah': 24.21, 'Ingrid': 91.19} # 遍历所有名字(两个字典键一致,取任意一个的键即可) for name in total_per_person: spent = total_per_person[name] budget = name_to_budget[name] difference = spent - budget if difference > 0: print(f"{name} 超支了:{difference:.2f} 元") elif difference < 0: print(f"{name} 低于预算:{abs(difference):.2f} 元") else: print(f"{name} 刚好花了预算的钱")
封装成函数更简便
编写函数确实更实用,核心优势包括:
- 逻辑模块化,代码整洁易读
- 可重复调用,后续有新的花费/预算字典时直接传参即可
- 可灵活扩展功能(比如处理无预算记录的情况、返回结构化结果等)
函数实现示例:
def check_budget_status(spent_dict, budget_dict): status_results = {} for name in spent_dict: if name not in budget_dict: status_results[name] = "无预算记录" continue spent = spent_dict[name] budget = budget_dict[name] difference = spent - budget if difference > 0: status_results[name] = f"超支 {difference:.2f}" elif difference < 0: status_results[name] = f"低于预算 {abs(difference):.2f}" else: status_results[name] = "刚好符合预算" return status_results # 调用函数 total_per_person = {'Edith': 79.24, 'Carol': 176.05, 'Hannah': 90.45, 'Frank': 66.6, 'Alice': 64.10, 'Ingrid': 59.45, 'Bob': 103.50, 'Gertrude': 107.45, 'Dave': 62.24} name_to_budget = {'Alice': 62.12, 'Bob': 40.34, 'Carol': 46.69, 'Dave': 37.79, 'Edith': 95.39, 'Frank': 32.87, 'Gertrude': 29.13, 'Hannah': 24.21, 'Ingrid': 91.19} results = check_budget_status(total_per_person, name_to_budget) # 打印结果 for name, status in results.items(): print(f"{name}: {status}")
内容的提问来源于stack exchange,提问作者user20481823
相关产品推荐
相关产品推荐

