Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否将新别名添加到现有词典?_Python_Dictionary_Alias - Fatal编程技术网

Python 是否将新别名添加到现有词典?

Python 是否将新别名添加到现有词典?,python,dictionary,alias,Python,Dictionary,Alias,因此,我尝试将一个新的“名称”作为别名添加到字典中现有的键中 例如: 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" 用户键入两个词:name以引

因此,我尝试将一个新的“名称”作为别名添加到字典中现有的键中

例如:

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"
用户键入两个词:name以引用“duck”,newname以指向现有键的值的新键。我是化名。 因此,当我更改
“duck”
的值时,
“newname”
也应该更改,反之亦然


我已经尝试了很多方法,但是没有找到一个好的方法来实现这一点。

没有内置的功能,但是在
dict
类型的基础上构建非常简单:

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"
别名。get(key,key)
如果没有别名,则返回
不变


处理键和别名的删除留给读者作为练习。

为什么您希望用户输入任意名称,然后将该名称用作变量?用户应输入名称,因为“名称”是“newname”应指向的别名。所以用户可以输入:duckplastic。现在plastic也应该引用值“yellow”。因此,
name
是现有的键,
newname
是插入到dict并指向相同值的新键,对吗?这是正确的@VinnyThis看起来很优雅;对原始密钥使用别名dict是解决此问题的一个很好的方法