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
  • 34,719
  • 24
  • 185
  • 251
IxDay
  • 3,587
  • 2
  • 21
  • 26

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
  • 464,258
  • 100
  • 912
  • 987
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
  • 59,056
  • 16
  • 119
  • 195