SoFunction
Updated on 2024-12-10

Python converts a dictionary into an object, which can be accessed using the "." way to access object property instances

I'm going to cut to the chase, so let's just go straight to the code!

database = [
  {
    "name": "18D_Block",
    "xcc":{  
      "component": {
        "core":[],
        "platform":[]
      },
    },
    "uefi":{  
      "component": {
        "core":[],
        "platform":[]
      },
    }
  }
]
class Dict(dict):
  __setattr__ = dict.__setitem__
  __getattr__ = dict.__getitem__
 
def dict_to_object(dictObj):
  if not isinstance(dictObj, dict):
    return dictObj
  inst=Dict()
  for k,v in ():
    inst[k] = dict_to_object(v)
  return inst
# Converts a dictionary into an object that can be accessed using the "." way to access object properties
res = dict_to_object(database[0])
print 
print 
print 
print 

Additional knowledge:[Python] Dictionary vars() function: extracting properties and attribute values of an object as a dictionary type

functionality

Extracts the properties and attribute values of an object, with a return value of dictionary type.

grammatical

vars(object)

an actual example

>>>print(vars())
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}

>>> class Test:
...   a = 1
... 

>>> print(vars(Test))
{'a': 1, '__module__': '__main__', '__doc__': None}

>>> test = Test()
>>> print(vars(test))
{}

For an assignment statement such as x = 1, we execute it with the name x referenced to the value 1. It's like a dictionary, where the keys refer to the values, but of course, the variables and their corresponding values are in an "invisible" dictionary. We can use the vars() function to return this dictionary:

>>> x = 1
>>> scope = vars()
>>> scope["x"]
1

Above this Python convert dictionary to object,can use "." way to access object properties example is all that I have shared with you, I hope to give you a reference, and I hope you support me more.