You need to enable JavaScript to run this app. Python SortedDict设置key参数出现str与int比较TypeError求助
优惠活动
大模型
产品
解决方案
定价
更多

Python SortedDict设置key参数出现str与int比较TypeError求助

错误产生原因
  • sortedcontainers库的SortedDict本身不支持用于自定义排序规则的key参数,你在构造函数中传入的key=lambda...会被识别为普通关键字参数,自动解析为键是字符串'key'、值为对应lambda表达式的键值对,插入到SortedDict中。
  • SortedDict默认按照键的自然顺序排序,插入后字典的键同时包含原输入的int类型键和新增的字符串类型键'key',Python不支持int和str类型直接用<比较,因此抛出类型错误。
修复方案

场景1:仅需要按键的自然顺序排序

直接删除构造函数中多余的key参数即可,你第一个可正常运行的写法就是正确实现:

from sortedcontainers import SortedDict
sd = SortedDict({1:2, 0:1}) 

场景2:需要自定义排序规则

SortedDict原生没有提供key参数支持自定义排序逻辑,可采用以下两种方案实现需求:

方案1:改用支持key参数的SortedList存储键值对

from sortedcontainers import SortedList
# 自定义排序规则:字符串类型键优先,int类型按键值升序排列
sl = SortedList({'a':2, 0:1}.items(), key=lambda item: 1 if isinstance(item[0], str) else item[0])
# 操作示例
print(dict(sl)) # 转换为普通字典可查看排序结果:{0: 1, 'a': 2}
sl.add(('b', 3)) # 插入新键值对

方案2:封装自定义键类实现比较逻辑

如果必须使用SortedDict,可以封装键的包装类,重写比较运算符:

from sortedcontainers import SortedDict

class CustomKey:
    def __init__(self, key):
        self.key = key
    # 重写小于比较运算符,自定义排序规则
    def __lt__(self, other):
        if isinstance(self.key, str) and isinstance(other.key, int):
            return True
        if isinstance(self.key, int) and isinstance(other.key, str):
            return False
        return self.key < other.key
    # 重写相等判断和哈希方法,保证键的唯一性和可哈希性
    def __eq__(self, other):
        return self.key == other.key
    def __hash__(self):
        return hash(self.key)

sd = SortedDict({CustomKey('a'):2, CustomKey(0):1})
print(sd[CustomKey(0)]) # 输出1

内容的提问来源于stack exchange,提问作者S.V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 18:42:03