0

Possible Duplicate:
Accessing dict keys like an attribute in Python?

Is there a way to implement this in python

foo = {'test_1': 1,'test_2': 2}
print foo.test_1
>>> 1

Maybe if I extend dict, but I do not know how to dynamically generate functions.

1
  • Unless you really really have to - don't... just use foo['test_1'] Commented Dec 11, 2012 at 17:38

2 Answers 2

1

How about:

class mydict(dict):
  def __getattr__(self, k):
    return self[k]

foo = mydict({'test_1': 1,'test_2': 2})
print foo.test_1

You might also want to override __setattr__().

Sign up to request clarification or add additional context in comments.

Comments

0

You can achieve a similar behavior using namedtuple. But the only drawback is, its immutable

>>> bar = namedtuple('test',foo.keys())(*foo.values())
>>> print bar.test_1
1
>>> print bar.test_2
2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.