在现有字典中添加新别名? [英] Adding a new alias to existing dictionary?

查看:125
本文介绍了在现有字典中添加新别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图添加一个新的名称

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

例如:

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 也应更改,反之亦然。

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.

推荐答案

没有内置功能,但是在 dict 类型的顶部构建起来很容易:

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

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.

这篇关于在现有字典中添加新别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆