Adding a new alias to existing dictionary?

Viewed 4501

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) here:")

#Somecode that allows me to input newname as an alias to "duck"

The user types two words: name to reference "duck", and newname a new key that should point to the value of the existing key. Ie an alias. So when I change the value for "duck" the "newname" should change too, and vice versa.

I've tried a lot of things but can't figure out a good way to do this.

1 Answers

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.

Related