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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
IxDay
  • 3,667
  • 2
  • 22
  • 27

2 Answers2

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__().

NPE
  • 486,780
  • 108
  • 951
  • 1,012
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
Abhijit
  • 62,056
  • 18
  • 131
  • 204