Python字典引用邻居字典元素 [英] Python dictionary reference to neighbor dictionary element

查看:155
本文介绍了Python字典引用邻居字典元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建以下内容:

I'm trying to create something following:

dictionary = {
   'key1': ['val1','val2'],
   'key2': @key1
}

其中@ key1是引用字典['key1']。
提前谢谢。

where @key1 is reference to dictionary['key1']. Thank You in advance.

推荐答案

我会扩展Aaron Digulla的版本。他现在在这里复制了:

I'd expand Aaron Digulla's version. What he has now is replicated here:

class DictRef(object):
    def __init__(self, d, key): self.d, self.key = d, key

d = {}
d.update({
    'key1': ['val1','val2'],
    'key2': DictRef(d, 'key1')
})

我假设他希望复制真正的引用语义,所以访问'key2'将永远给你一种方法来获得任何'key1' 具有一个值。问题是 d ['key1'] 是一个列表 d ['key2 '] 是一个 DictRef 。所以要获得'key1'的值,所需要做的只是 d ['key1'] 但是对于'key2',您必须执行 d [d ['key2'] .key] 。此外,您不能引用一个正常工作的引用,它将成为 d [d [d ['key2'] .key] .key] 。您如何区分参考和常规值?可能通过使用isinstance进行类型检查(v,DictReference)( ew )。

I assume he wishes to replicate true reference semantics, so that accessing 'key2' will always give you a way to get to whatever 'key1' has as a value. the problem is while d['key1'] is a list, d['key2'] is a DictRef. So to get the "value" of 'key1' all you need to do is d['key1'], but for 'key2' you must do d[d['key2'].key]. Furthermore, you can't have a reference to a reference that works sanely, it would become d[d[d['key2'].key].key]. And how do you differentiate between a reference and a regular value? Probably through typechecking with isinstance(v, DictReference) (ew).

所以我有一个建议来解决所有这些。

So I have a proposal to fix all of this.

个人而言,我不明白为什么需要真正的引用语义。如果看起来有必要,可以通过重组问题或解决问题来使其变得不必要。甚至可能它们并不是必需的,一个简单的 d.update(key2 = d ['key1'])将会解决这个问题。

Personally, I don't understand why true reference semantics are necessary. If they appear necessary, they can be made unnecessary by restructuring the problem, or the solution to the problem. It may even be that they were never necessary, and a simple d.update(key2=d['key1']) would have solved the issue.

无论如何,对于提案:

class DictRef(object):
    def __init__(self, d, key): 
        self.d = d
        self.key = key

    def value(self):
        return self.d[self.key].value()

class DictVal(object):
    def __init__(self, value):
        self._value = value

    def value(self):
        return self._value

d = {}
d.update(
    key1=DictVal(['val1', 'val2']),
    key2=DictRef(d, 'key1')
)

现在,为了获得任何键的值,无论是否引用,只需执行 d [k] .value()。如果引用引用,它们将被正确地链接解除引用。如果它们形成一个非常长的或无限的链,Python将失败并带有RuntimeError以进行过度递归。

Now, in order to get the value of any key, whether it's a reference or not, one would simply do d[k].value(). If there are references to references, they will be dereferenced in a chain correctly. If they form a really long or infinite chain, Python will fail with a RuntimeError for excessive recursion.

这篇关于Python字典引用邻居字典元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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