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

Python2迁移至Python3遇字典取值错误:'int'对象不可下标访问

Fixing the TypeError: 'int' object is not subscriptable in Python3 Migration

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 str and bytes as completely separate types—so even if the content matches, b'Aabenraa' won't match the 'Aabenraa' key in your dictionary. Hence, get() returns 0.

Step-by-Step Fix

  1. Remove the encode("utf-8") call
    Since Python 3 uses Unicode strings by default, your dictionary keys and data.kommune should already be compatible. Change the key line to:

    key = data.kommune.strip()
    
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:26:35