0

In Lua you can address keys of the dictionary like attributes:

d = {a = 1, b = 1}
d['a'] == d.a -- this returns true

Is there something like that in Python? I've noticed that sklearn bunch objects have similar properties.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Ulysses
  • 357
  • 1
  • 13
  • 2
    possible duplicate of [Convert Python dict to object?](http://stackoverflow.com/questions/1305532/convert-python-dict-to-object) – kylieCatt Jun 24 '15 at 12:03
  • I guess, one of the reasons that Lua uses `d.a` a syntax sugar of `d['a']` is that Lua uses `t:func()` in its own unique OOP style. That's not the case for Python. – Yu Hao Jun 24 '15 at 12:10

2 Answers2

4

No, the only valid ways to access a dict using a key are d['a'] or d.get('a')

The former may raise a KeyError if that key is not in the dict, and the latter takes a second optional argument that it will return if the key is not found.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

You can make a class and use setattr to access attributes that way, though it seems kinda excessive just for convenience. You could do it with any old object too, but I wouldn't recommend it.

Rob Foley
  • 601
  • 4
  • 6