当我需要一个自我参考字典时,该怎么办? [英] What do I do when I need a self referential dictionary?

查看:100
本文介绍了当我需要一个自我参考字典时,该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很熟悉Python,令人惊讶的是我无法做到这一点。

  dictionary = {
'a':'123',
'b' a'] +'456'
}

我想知道Pythonic的方式在我的脚本中正确地做到这一点,因为我觉得我不是唯一一个尝试这样做的人。



编辑:人们正在想知道我在做什么,所以这里有更多的细节用于我的用例。说我想保持字典对象保存文件系统路径。路径是相对于字典中的其他值。例如,这是我的一个字典可能看起来像。

  dictionary = {
'user':' sholsapp',
'home':'/ home /'+字典['user']
}

重要的是,在任何时候,我可以更改 dictionary ['user'] ,并且所有的字典值都反映了更改。再次,这是我使用它的示例,所以我希望它传达我的目标。



从我自己的研究我想我将需要实现一个类来执行此操作。

解决方案

不要担心创建新课程 -
你可以利用Python的字符串形成能力
,只需执行以下操作:

  class MyDict(dict):
def __getitem __(self,item):
return dict .__ getitem __(self,item)%self

dictionary = MyDict({

'user':'gnucom ',
'home':'/ home /%(user)s',
'bin':'%(home)s / bin'
})


打印字典[home]
打印字典[bin]


I'm new to Python, and am sort of surprised I cannot do this.

dictionary = {
    'a' : '123',
    'b' : dictionary['a'] + '456'
}

I'm wondering what the Pythonic way to correctly do this in my script, because I feel like I'm not the only one that has tried to do this.

EDIT: Enough people were wondering what I'm doing with this, so here are more details for my use cases. Lets say I want to keep dictionary objects to hold file system paths. The paths are relative to other values in the dictionary. For example, this is what one of my dictionaries may look like.

dictionary = {
    'user': 'sholsapp',
    'home': '/home/' + dictionary['user']
}

It is important that at any point in time I may change dictionary['user'] and have all of the dictionaries values reflect the change. Again, this is an example of what I'm using it for, so I hope that it conveys my goal.

From my own research I think I will need to implement a class to do this.

解决方案

No fear of creating new classes - You can take advantage of Python's string formating capabilities and simply do:

class MyDict(dict):
   def __getitem__(self, item):
       return dict.__getitem__(self, item) % self

dictionary = MyDict({

    'user' : 'gnucom',
    'home' : '/home/%(user)s',
    'bin' : '%(home)s/bin' 
})


print dictionary["home"]
print dictionary["bin"]

这篇关于当我需要一个自我参考字典时,该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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