Python中如何按指定id选中对应字典并更新其内容?
功能实现方案
你现有代码的更新逻辑默认仅能修改最后一条录入的交易记录,只要在更新分支新增目标交易ID的录入和校验逻辑即可实现按指定ID修改的需求,修改后的完整代码如下:
cont = {} n = int(input("Insert the number of transactions:")) if n == 0: print("Going to the next option") else: for i in range(0, n): tranz = input("Insert the id of the transaction: ") ziua = input("Insert the day: ") suma = input("Insert the amount: ") tipul = input("Insert the type(int/out): ") # 原有代码中未使用的tranz_key变量可直接删除 cont[tranz] = {"day": ziua, "amount": suma, "type": tipul} k = input("Do you wish to update something?(Yes/No): ") if k == 'No': print("Going to the next option") else: # 新增:获取用户要修改的目标交易ID target_id = input("Insert the ID of the transaction you want to modify: ") # 校验ID是否存在,避免KeyError报错 if target_id not in cont: print(f"Transaction ID {target_id} does not exist!") else: y = input("Insert a new day (leave blank to keep original value):") if len(y) != 0: cont[target_id].update({"day": y}) z = input("Insert a new amount (leave blank to keep original value):") if len(z) != 0: z = int(z) cont[target_id].update({"amount": z}) w = input("Insert a new type(in/out) (leave blank to keep original value):") if len(w) != 0: cont[target_id].update({"type": w}) # 测试用代码,不需要可直接删除 print("Current transaction records: ", cont)
核心改动说明
- 进入更新逻辑后先采集目标交易ID,先判断ID是否在存储交易的
cont字典中,不存在直接返回提示避免运行报错 - 将原逻辑中固定使用最后一次录入的
tranz变量替换为用户输入的target_id,实现精准修改指定ID的交易记录 - 优化输入提示,标注留空可保留原有值,使用体验更友好
内容的提问来源于stack exchange,提问作者Morph3us
相关产品推荐
相关产品推荐

