Home > Enterprise >  access dict element with dot
access dict element with dot

Time:09-08

I try to access element of dict with dot but not work:

x = {'key':'value'}
print(x.key)

it report error:

AttributeError: 'dict' object has no attribute 'key'

CodePudding user response:

dictionaries cannot be acces via a dot. to acces dictionaries used

my_dict["my_key"]
my_dict.get("my_key")

if you want such an object I suggest using named tuples or dataclasses (named tuples are lighter).

from collections import namedtuple

MyName = namedtuple('MyName', 'key1 key2')

my_obj = MyName(**{"key1": 2.5, "key2": 1.5})
my_obj.key1
>>> 2.5
  • Related