Skip to content Skip to sidebar Skip to footer

Adding A New Alias To Existing Dictionary?

So I'm trying to add a new 'name' as an alias to an existing key in a dictionary. for example: dic = {'duck': 'yellow'} userInput = raw_input('Type the *name* and *newname* (alias

Solution 1:

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.


Post a Comment for "Adding A New Alias To Existing Dictionary?"