Python2迁移至Python3遇字典取值错误:'int'对象不可下标访问
Hey there! Let's break down why this error is popping up and fix it for you.
What's Causing the Error?
The line laP = float(rd[0]) is throwing a TypeError because rd is the integer 0 at that point—not the list you expect. This happens when myDict.get(key.strip(), 0) can't find the key in your dictionary, so it returns the default value 0.
The root issue is a Python 2 vs Python 3 string/bytes difference:
- In your dictionary
myDict, all keys are regular Unicode strings (like'Aabenraa'). - In Python 3,
data.kommune.encode("utf-8")converts the string to a bytes object (e.g.,b'Aabenraa'). - Python 3 treats
strandbytesas completely separate types—so even if the content matches,b'Aabenraa'won't match the'Aabenraa'key in your dictionary. Hence,get()returns0.
Step-by-Step Fix
Remove the
encode("utf-8")call
Since Python 3 uses Unicode strings by default, your dictionary keys anddata.kommuneshould already be compatible. Change the key line to:key = data.kommune.strip()Add a safety check for missing keys
To avoid similar errors if a kommune isn't in your dictionary, update the code to handle missing keys gracefully:myDict = littleUglyDataCollectionInTheSourceCode() key = data.kommune.strip() rd = myDict.get(key) # No default value here—returns None if key is missing if rd is None: print(f"Warning: Kommune '{key}' not found in the data!") # Handle this case (e.g., return a default value, log an error, etc.) return # Or adjust based on what your function needs to do laP = float(rd[0]) # average precipitation midV = float(rd[1]) # Middelværdi Klimagrid
Why This Worked in Python 2
In Python 2, strings (str) were essentially byte strings, and Unicode strings were unicode objects. When you called encode("utf-8") on a Python 2 unicode string, you got a str object that matched the keys in your dictionary. Python 3's strict separation of str (Unicode) and bytes breaks this compatibility.
Give these changes a try—your code should now correctly fetch the list from the dictionary and avoid the TypeError!
内容的提问来源于stack exchange,提问作者Rasmus Kierudsen

