Make Python dict accessible by Attribute

Motivation

In Python, unlike JavaScript etc., dictionary elements cannot be accessed by Attribute. In other words, dict_obj ["value "] is OK, but not dict_obj.value.

The inconvenience this is when working with Json data. After all, on the JavaScript side, it can be accessed with Attribute, so it is human nature to want to write in the same way.

That's why I will show you how to access dict (assuming Json object this time) with Attribute.

Implementation

In Python, loading Json makes it a dictionary.

>>> import json
>>> json.loads('{"v1":"xxxx", "v2":"vvvv"}')
{'v1': 'vvvv', 'v2': 'xxxx'}

As mentioned above, when accessing, it will be in the form of ʻobj ["v1"] and ʻobj.vi will be NG.

The easiest way to solve this is to use a library called attrdict.

However, if you don't want to install it, you can use the following simple method. When doing json.loads, use ʻobject_hook to wrap each object in a class that implements attribute access ( getattr`). You can now access the element via Attribute.

import json

class AttributeDict(object):
    def __init__(self, obj):
        self.obj = obj

    def __getstate__(self):
        return self.obj.items()

    def __setstate__(self, items):
        if not hasattr(self, 'obj'):
            self.obj = {}
        for key, val in items:
            self.obj[key] = val

    def __getattr__(self, name):
        if name in self.obj:
            return self.obj.get(name)
        else:
            return None

    def fields(self):
        return self.obj

    def keys(self):
        return self.obj.keys()

if __name__ == "__main__":
    attribute_json = json.loads('{"v1":"xxxx", "v2":"vvvv"}', object_hook=AttributeDict)
    print("attribute_json.v1 = {0}".format(attribute_json.v1))

    json_with_array = json.loads('{"arr":[{"v":"xxxx"}, {"v":"vvvv"}]}', object_hook=AttributeDict)
    print("json_with_array[0].v = {0}".format(json_with_array.arr[0].v))

Execution result

attribute_json.v1 = xxxx
json_with_array[0].v = xxxx

If you can access Attribute, you will be able to complete the code, so it will be easier to implement. I tried it.

reference

attrdict using JSON keys as python attributes in nested JSON soundcloud-python/resource.py Sample on Gist

Recommended Posts

Make Python dict accessible by Attribute
python / Make a dict from a list.
Make Python dictionaries accessible as attributes
Alternative: Make Python dictionaries accessible as attributes
[Python] [R] Make GPU recognized by tensorflow-2.x
Python Dict category
Python attribute alias
Primality test by Python
Communication processing by Python
How to achieve access by attribute and retention of insertion order in Python dict
[Python] Get element by specifying name attribute in BeautifulSoup
Beamformer response by python
[Python] How to make a list of character strings character by character
Speech recognition by Python MFCC
Sort by dict type value value
How Python __dict__ is used
EXE Web API by Python
Make MeCab available from Python3
Newcomer training program by Python
Parameter setting by python configparser
Python basic dict sort order
Pin python managed by conda
Use list-keyed dict in Python
Make Jupyter Lab accessible remotely
Make Puyo Puyo AI with Python
Don't make test.py in Python!
Keyword extraction by MeCab (python)
Separate numbers by 3 digits (python)
Make a bookmarklet in Python
Make a fortune with Python
Make Opencv available in Python
Markov switching model by Python
Make python segfault in 2 lines
Image processing by python (Pillow)
Python started by C programmers
Platform (OS) determination by Python
Sort by date in python
Join csv normalized by Python pandas to make it easier to check