Home > Software design >  Access Dict with both dot notation and normal notation
Access Dict with both dot notation and normal notation

Time:03-03

I have one dictionary

a = {'ID': 12, 'sw': 'sweet'}

I want to access the ID key with dot notation.

a.ID = 12

and want to access sw key with normal notation.

a['sw']= 'sweet'

On the same dictionary. Is it possible to do so?

I want to perform this operation in python 3.6 env.

CodePudding user response:

Creating this class would allow both

class dotdict(dict):
    """dot.notation access to dictionary attributes"""
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

mydict = {'val':'it works'}
mydictclass = dotdict(mydict)

print(mydictclass['val'])
print(mydictclass.val)

CodePudding user response:

your question isn't very understandable, if you want to create a "normal" dictionary with a variable called ID that you can access with dot notation you can use the following class that extends dictionary

class DictWithId(dict):
    def __init__(self, id=None):
        super().__init__()
        self.ID = id

calling the dictionary __init__ function and then set the ID variable that yo can use as you mentioned

# create our dictionary class
a = DictWithId()

# set the id directly with the ID variable
a.ID = 5

# set the 'sw' to 'sweet' like a normal dictionary
a['sw'] = 'sweet'

# print out to test that everything is good
print(a.ID, a['sw'])

note: you can expand this class and add other functions that you might need like __str__ to print and test this class.

  • Related