You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典键重分配遇UnboundLocalError报错求助

问题解决:UnboundLocalError 处理方案

错误原因

当你在addBullet函数中执行brands = update_keys(brands)时,Python会将brands标记为局部变量。但在此之前的entries_to_remove(entries, brands)语句中,你试图使用这个尚未完成赋值的局部变量,直接触发了UnboundLocalError。本质是:函数内只要出现对变量的赋值操作,Python就会将其视为局部变量,不再引用全局作用域的同名变量。

解决方法

提供两种可行的处理方式:

方法1:使用global声明全局变量

在addBullet函数开头声明brands为全局变量,让函数内的赋值操作直接作用于全局字典:

def addBullet():  
    global brands  # 声明使用全局变量brands
    name = str(input('Enter bullet name: '))
    print('Choose cartridge type')
    print_menu(cartridge_types)
    cType = cartridge_types.get(int(input()))
    if cType == cartridge_types.get(1):
        entries = (2, 3, 4, 6, 9, 10)
        entries_to_remove(entries, brands)
        brands = update_keys(brands)
        
    print('Choose brand')
    print_menu(brands)
    brand = brands.get(int(input()))

方法2:重构逻辑,避免修改全局变量

更推荐这种方式,通过创建字典副本处理,避免全局变量被意外修改,适合后续多次复用场景:

def addBullet():  
    name = str(input('Enter bullet name: '))
    print('Choose cartridge type')
    print_menu(cartridge_types)
    cType = cartridge_types.get(int(input()))
    
    # 基于全局brands创建副本,所有操作仅作用于副本
    filtered_brands = brands.copy()
    if cType == cartridge_types.get(1):
        entries = (2, 3, 4, 6, 9, 10)
        entries_to_remove(entries, filtered_brands)
        filtered_brands = update_keys(filtered_brands)
        
    print('Choose brand')
    print_menu(filtered_brands)
    brand = filtered_brands.get(int(input()))

额外优化建议

你的update_keys函数可以简化,同时避免遍历原字典键的潜在顺序问题:

def update_keys(dictionary):
    # 按原字典值的顺序生成连续键的新字典
    return {i+1: val for i, val in enumerate(dictionary.values())}

内容的提问来源于stack exchange,提问作者Francesco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 13:23:21