My function is like
def calResult(w,t,l,team):
wDict={}
for item in team:
for x in w:
wDict[item]=int(wDict[item])+int(x[item.index(" "):item.index(" ")+1])
for x in t:
wDict[item]=int(wDict[item])+int(x[item.index(" "):item.index(" ")+1])
return wDict
say I create the empty dict then I use wDict[item]
to assign value for each key(these are from a team list, we have team like abc d...). the x[item.index(" "):item.index(" ")+1]
part will return a value after the int method have run. But the python shell returned that
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 66, in <module>
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 59, in calResult
builtins.KeyError: 'Torino'
I can't understand what exactly is the error in my code.
I'm not quite sure what you're trying to do here (consider using more descriptive variable names than x
, for starters), but here is the problem:
wDict[item]=int(wDict[item])+...
The first time you do this, wDict[item]
doesn't exist, hence the KeyError
.
What you want, I think, is:
wDict[item] = wDict.get(item, 0) + int(x[item.index(" "):item.index(" ")+1])
.get()
takes a key and a default value to use if that key doesn't exist.
You might also want to use the Counter
class in collections
, which is designed to default nonexistent keys to zero for just this sort of situation.
You can not access wDict[item]
the first time, since your dict is empty
This would be ok:
wDict[item] = 1
But you can not do this :
wDict[item] = wDict[item] + 1
Maybe you want to use this syntax :
wDict[item] = int(wDict.get(item, 0)]) + int(x[item.index(" "):item.index(" ") + 1])
Looks like you are trying to use wDict[item] as the rvalue and the lvalue in the same assignment statement, when wDict[item] is not yet initialized.
wDict[item]=int(wDict[item])+int(x[item.index(" "):item.index(" ")+1])
You are trying to access the "value" of the key item, but there is no key value pair initialized.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.