且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在现有字典中添加新别名?

更新时间:2023-11-23 22:34:10

没有内置功能,但是在 dict 类型的顶部构建起来很容易:

There's no built-in functionality for this, but it's easy enough to build on top of the dict type:

class AliasDict(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self.aliases = {}

    def __getitem__(self, key):
        return dict.__getitem__(self, self.aliases.get(key, key))

    def __setitem__(self, key, value):
        return dict.__setitem__(self, self.aliases.get(key, key), value)

    def add_alias(self, key, alias):
        self.aliases[alias] = key


dic = AliasDict({"duck": "yellow"})
dic.add_alias("duck", "monkey")
print(dic["monkey"])    # prints "yellow"
dic["monkey"] = "ultraviolet"
print(dic["duck"])      # prints "ultraviolet"

aliases.get(key,key)返回 key 如果没有别名,则保持不变。

aliases.get(key, key) returns the key unchanged if there is no alias for it.

留给读者处理密钥和别名的删除操作。

Handling deletion of keys and aliases is left as an exercise for the reader.