-2

I like to know is there way to access elements in an object using .(dot) operator (show_letters.a) without creating a class. I know I can access in following way

def show_letters(letters):
    print(letters['a'])


def main():
    letters = {"a": 2, "b": 3, "c":4}
    show_letters(letters)

main()

how can access show_letters.a or is it possible?

SamL
  • 37
  • 1
  • 10
  • 1
    What? Neither `show_letters` (the function) not `letters` (the dictionary) have an `a` attribute. And how is that related to the arguments? What output are you expecting? – jonrsharpe Nov 02 '18 at 22:22
  • 4
    Here is the answer (you should extends default dict class): https://stackoverflow.com/questions/2352181/how-to-use-a-dot-to-access-members-of-dictionary – Ivan Podhornyi Nov 02 '18 at 22:23
  • 1
    the dot notation is for attributes of a class object. The square brackets are for indexing and slicing, a la `letters['a']`. The parentheses are for calling a function (or method of a class). Those are not interchangeable. (With the exception of a few cases, like pandas columns, which should really be called with `[]` anyway, but that's just my (correct) opinion) – G. Anderson Nov 02 '18 at 22:27

1 Answers1

1

If what you want to do is access a value in a dictionary with the dot operator, you're not going to be able to do it without creating a class. It would be class that inherits from dict and overrides the __getattr__ method. Dictionaries do have the get method though, I would use that one.

You could save your data as attributes of any object too, but that's not really a good idea.

Pablo Paglilla
  • 366
  • 2
  • 5