【问题标题】:Python Dictionary Throwing KeyError for Some ReasonPython字典由于某种原因引发KeyError
【发布时间】:2013-06-21 03:28:27
【问题描述】:

在某些代码中,我通过字典 (TankDict) 从列表中传递一个字符串。无论我输入什么字母,这都会引发 KeyError。当我从程序的上下文中复制并粘贴字典并从列表中传入相同的字母时,它们正确地出来了。我还运行了type(TankDict),它以“dict”的形式返回。 这是字典: TankDict = {'E':0, 'F':1, 'G':2, 'H':3, 'I':4, 'J':5, 'K':6, 'L':7, 'M':8, 'N':9, 'O':10, 'P':11, 'Q':12, 'R':13, 'S':14, 'T':15, 'U':16, 'V':17, 'W':18, 'X':19}

错误: enter code herechannelData[1] = tank_address_dict[channelData[1]] KeyError: 'L' (tank_address_dict 是 TankDict 传入的函数参数)

channelData的内容:['447', 'L', '15', 'C']

谁能告诉我发生这种情况的(可能很简单)原因?

编辑:代码!

这是错误所在的函数:

def getTankID(channel,tank_address_dict,PTM_dict,channel_ref):
rawChannelData = 'NA' 
for line in channel_ref:
    if str(channel) in line: rawChannelData = line
if(rawChannelData == 'NA'): return -1;
channelData = rawChannelData.split(' ')
channelData.extend(['',''])
channelData[1] = channelData[1][:-1]
channelData[3] = channelData[1][-1]
channelData[1] = channelData[1][:-1]
channelData[2] = channelData[1][1:]
channelData[1] = channelData[1][:1]
print channelData #debug
print 'L' in tank_address_dict
print 'E' in tank_address_dict
print 'O' in tank_address_dict
print 'U' in tank_address_dict
print type(tank_address_dict)
channelData[1] = tank_address_dict[channelData[1]]
channelData[3] = PTM_dict[channelData[3]]
return(channelData[1:])

这是调用它的函数:

def runFile(model, datafile, time_scale, max_PEs, tank_address_dict, PMT_dict, channel_ref):
#add initSerial for ser0-4
while(True):   
    raw_data = datafile.readline() #intake data
    if(raw_data == ''): break #End while loop if the file is done
    data = raw_data.split(' ')  #break up the parts of each line
    del data[::2]   #delete the human formatting
    data[2] = data[2][:-1] #rm newline (NOTE: file must contain blank line at end!)
    TankID = getTankID(data[0], tank_address_dict, PMT_dict,channel_ref)
    if(TankID == -1):
        print '!---Invalid channel number passed by datafile---!'; break #check for valid TankID
    model[TankID[0]][TankID[1]][TankID[2]] = scale(data[2],(0,max_PEs),(0,4096))
    createPackets(model)
    #updateModel(ser0,ser1,ser2,ser3,ser4,packet)
    data[2] = data[2]*time_scale #scale time
    time.sleep(data[2]) #wait until the next event
    print data #debug 
if(TankID != -1): print '---File',datafile,'finished---' #report errors in file run
else: print '!---File',datafile,'finished with error---!' 

这是调用它的代码:

import hawc_func
import debug_options
#begin defs
model = hawc_func.createDataStruct() #create the data structure
TankDict = hawc_func.createTankDict() #tank grid coordinate conversion table
PTMDict = hawc_func.createPMTDict() #PMT conversion table
log1 = open('Logs/log1.txt','w') #open a logfile
data = open('Data/event.txt','r') #open data
channel_ref = open('aux_files/channel_map.dat','r')
time_scale = 1 #0-1 number to scale nano seconds? to seconds
#end defs
hawc_func.runFile(model,data,4000,TankDict,PTMDict,time_scale,channel_ref)

#hawc_func.runFile(model,data,TankDict,PTMDict)
#close files
log1.close()
data.close()
#end close files
print '-----Done-----' #confirm tasks finished

tank_address_dict 是通过这个函数创建的,由第三个代码块运行,然后通过其他两个传递:

def createTankDict():
    TankDict = {'E':0, 'F':1, 'G':2, 'H':3, 'I':4, 'J':5,
               'K':6, 'L': 7, 'M':8, 'N':9,
               'O':10, 'P':11, 'Q':12, 'R':13, 'S':14, 'T':15,
               'U':16, 'V': 17, 'W':18, 'X':19}
    return TankDict

【问题讨论】:

  • 请显示您的实际代码以及完整的错误消息。
  • 你能显示你的代码吗?函数调用,函数定义?
  • 你说tank_addres_dict() 将字典作为参数,然后你将它传递给一个字符串?
  • 您是否在混合使用 unicode 和 ascii 字符串?
  • 再给我一分钟来添加代码...把我的修改弄混了

标签: python dictionary


【解决方案1】:

您没有正确传递参数。

def runFile(model, datafile, time_scale, max_PEs, tank_address_dict, PMT_dict, channel_ref):

hawc_func.runFile(model,data,4000,TankDict,PTMDict,time_scale,channel_ref)

这里,你有max_PEs = TankDict

这可能不是您唯一的问题。先解决这个问题,如果您仍然遇到问题,请使用您的固定代码更新您的帖子,然后告诉我们您的新错误是什么。

【讨论】:

  • 我建议你使用关键字 args。如runFile(model=None, datafile=None, ...) 等。如果你这样做,你需要确保在没有定义所有参数的情况下不要调用函数——但这应该有助于你避免参数错误。
猜你喜欢
  • 1970-01-01
  • 2018-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 2021-04-13
  • 1970-01-01
相关资源
最近更新 更多