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

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

问题描述

我是 Python 新手,有点惊讶我不能这样做.

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

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

我想知道在我的脚本中正确执行此操作的 Pythonic 方法是什么,因为我觉得我不是唯一尝试这样做的人.

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.

有足够多的人想知道我在用这个做什么,所以这里有更多关于我的用例的细节.假设我想保留字典对象来保存文件系统路径.路径相对于字典中的其他值.例如,这就是我的一本词典的样子.

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']
}

重要的是,我可以随时更改 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.

推荐答案

不怕创建新类 -您可以利用 Python 的字符串格式化功能只需执行以下操作:

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天全站免登陆