Skip to main content

Python Dictionary Representation

Description

The DictRepr class is an abstract base class that enables any subclass to define its own dictionary representation. This makes it possible to do:

dict_repr = dict(arbitrary_object)

The subclass only needs to do two things:

  • Override the keys() instance method to return a list of strings
  • Have the keys map to variables or properties on that object

Example

lass MyArbitraryClass(DictRepr):

    _keys = ["uppercase", "length"]

    def __init__(self, value: str):
        self._value = value

    @property
    def uppercase(self):
        return self._value.upper()

    @property
    def length(self):
        return len(self._value)

    def keys(self):
        return self._keys


if __name__ == "__main__":
    myobj = MyArbitraryClass("Hello World")
    mydict = dict(myobj)
    print("mydict type: {}".format(type(mydict)))
    pprint(mydict)
$ python3 examples/dict_repr_example.py
mydict type: <class 'dict'>
{'length': 11, 'uppercase': 'HELLO WORLD'}

Mapping Keys to Object Attributes

It may be the case that a desired dicitonary key isn't the name of the corresponding attribute. For example, a string may have spaces or other characters that, while perfectly suitable as a dictionary key, make it illegal as an object attribute name.

In this case, the KeyTuple class provides a mapping between key string and attribute name. Simply include a KeyTuple object in place of the key string:

_keys = [
    KeyTuple("string with spaces 1", "no_spaces_1"),
    KeyTuple("string with spaces 2", "no_spaces_2")
]

KeyTuple Example

Let's modify the previous example:

from py_dict_repr import DictRepr, KeyTuple
class MyArbitraryClass(DictRepr):

    _keys = [
        KeyTuple("uppercase verion", "uppercase"),
        KeyTuple("string length", "length"),
        # KeyTuple may be mixed with regular key strings
        "lowercase"
    ]

    def __init__(self, value: str):
        self._value = value

    @property
    def uppercase(self):
        return self._value.upper()

    @property
    def lowercase(self):
        return self._value.lower()

    @property
    def length(self):
        return len(self._value)

    def keys(self):
        return self._keys


if __name__ == "__main__":
    myobj = MyArbitraryClass("Hello World")
    mydict = dict(myobj)
    print("mydict type: {}".format(type(mydict)))
    pprint(mydict)
$ python3 examples/dict_repr_example.py
python3 ./examples/dict_repr_keytuple_example.py
mydict type: <class 'dict'>
{string length: 11, uppercase verion: 'HELLO WORLD', 'lowercase': 'hello world'}

Metadata

Release files for py-dict-repr 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for py-dict-repr 0.1.2
File Size Uploaded
py-dict-repr-0.1.2.tar.gz 4.0 kB Details

Release files / py-dict-repr-0.1.2.tar.gz

Download URL py-dict-repr-0.1.2.tar.gz
Size 4.0 kB
Tags Source
SHA-256 checksum
How to use checksums
fe8f56cfaa79bacebcbfb9d9adf1484c7cf1dcc42587cdc90f7d9b1eeab1efde
BLAKE2b-256 checksum
How to use checksums
66d9c105866a3dcba3b12f6d4a2ad1471afa6b27d12291ea304d18b80082927f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.7.0 importlib_metadata/3.10.0 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.51.0 CPython/3.9.9
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page