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

如何实现支持键顺序比较的特殊Python字典类型?

问题

假设我有如下字典:

some_dict = {"START": "something", "MAIN": "something", "END": "something"}

我希望能像下面这样比较键的顺序:

for key in some_dict.keys():
    if key < "MAIN":
        print(f"键 '{key}' 在 'MAIN' 之前")
    elif key > "MAIN":
        print(f"键 '{key}' 在 'MAIN' 之后")

我知道字典的键本质是字符串,默认会按照字符串的规则进行比较,但有没有一种特殊的字典类型,能让键支持按实际存储顺序进行比较?

更新:我的实现方案

感谢MisterMiyagi、@PoneyUHC、@Achille G提出的list.index(elem)方案,但这种方法需要修改比较逻辑本身。我想要的是一个类似字典的新类,让它的键支持按顺序比较,实现代码如下:

from typing import List, TypeVar

KT = TypeVar('KT')
VT = TypeVar('VT')


def def_compareable_keyclass(nobj, index):
    class CK(type(nobj)):
        def __init__(self, some_obj) -> None:
            type(nobj).__init__(some_obj)
            self.order_based_comparison_index = index

        def __lt__(self, other) -> bool:
            return self.order_based_comparison_index < other.order_based_comparison_index

        def __le__(self, other) -> bool:
            return self.order_based_comparison_index <= other.order_based_comparison_index

        def __gt__(self, other) -> bool:
            return self.order_based_comparison_index > other.order_based_comparison_index

        def __ge__(self, other) -> bool:
            return self.order_based_comparison_index >= other.order_based_comparison_index

        def __eq__(self, other) -> bool:
            return self.order_based_comparison_index == other.order_based_comparison_index

        def __ne__(self, other) -> bool:
            return self.order_based_comparison_index != other.order_based_comparison_index

    return CK


class not_dict(dict[KT, VT]):
    def keys(self) -> List[KT]:
        s_keys = super().keys()
        r_keys: List[KT] = []
        for i, key in enumerate(s_keys):
            r_keys.append(def_compareable_keyclass(key, i)(key))
        return r_keys

这个实现可以正常运行:

some_dict = not_dict({"START": "something", "MAIN": "something", "END": "something"})

pivot = some_dict.keys()[1]

for key in some_dict.keys():
    if key < pivot:
        print(f"键 '{key}' 在 '{pivot}' 之前")
    elif key > pivot:
        print(f"键 '{key}' 在 '{pivot}' 之后")
    elif key == pivot:
        print(f"键 '{key}' 就是 '{pivot}'")

输出结果:

键 'START' 在 'MAIN' 之前
键 'MAIN' 就是 'MAIN'
键 'END' 在 'MAIN' 之后

内容的提问来源于stack exchange,提问作者MPEI_stud

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 22:03:31