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:
classAliasDict(dict):
def__init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.aliases = {}
def__getitem__(self, key):
returndict.__getitem__(self, self.aliases.get(key, key))
def__setitem__(self, key, value):
returndict.__setitem__(self, self.aliases.get(key, key), value)
defadd_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?"