0

I have a set of keywords which contain a default value. Say:

a_dict =\
{'key1': 'value1'
'key2': 'value2'
... and so on ...}

I don't want to use a dict because I find it annoying having to type:

a_dict['key2']

in order to get the keyword's value. I would like to have all of these keywords available on a variable (say var) so that when I press 'Tab Key' after $var.$ I get all posible keywords. I have tried with $namedtuple$ from $collections$ module but I run in the problem where I can't modify none of the values of each key (because it is a touple). The good thing of namedtuple is that I could iterate over it, for example:

for key in var:
    #do something with key

What I did is to create a class named Keys as shown next:

class Keys(object):
    def __init__(self):
        self.key1 = 'value1'
        self.key2 = 'value2'
        ... and so on...

Now when I do:

keys = Keys()

I have all the namespace available in keys. and can modify all values of each key. The problem is that now I cannot iterate over each key. And I don't know how to set __getitem__ method in order to iterate over the instance keys.

The perfect solution would be to use a namedlist function (similar to namedtuple) but I don't know any similar function. Is there one?

How can I do it? Any other alternative will be wellcome. Thanks in advance.

ezitoc
  • 729
  • 1
  • 6
  • 9

1 Answers1

0

Something like this?

def __getitem__(self, key):
        try:
            return getattr(self, key) 
        except:
            raise AttributeError('%s is not a valid property'%key)
M4rtini
  • 13,186
  • 4
  • 35
  • 42
  • I think maybe this is the inverse of the question, which is to access dict items using attribute notation. – askewchan Dec 10 '13 at 23:40
  • Ahh, maybe this is what you need? http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python – M4rtini Dec 10 '13 at 23:42
  • Ha I just found that too :P – askewchan Dec 10 '13 at 23:45
  • My apologies for this duplicate. I work at home with no internet connection so I prepared the question at home. I had very little time to post the question and could not investigate the problem. Can I erase the question? – ezitoc Dec 11 '13 at 19:09