Adding a new alias to existing dictionary?

前端 未结 1 1545
广开言路
广开言路 2021-01-23 23:20

So I\'m trying to add a new "name" as an alias to an existing key in a dictionary.

for example:

dic = {"duck": "yellow"}

use         


        
相关标签:
1条回答
  • 2021-01-23 23:29

    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) 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.

    0 讨论(0)
提交回复
热议问题