Created
August 16, 2020 13:57
-
-
Save ghukill/3c0d841222cfe8995d421017b911243e to your computer and use it in GitHub Desktop.
dot notation object from python dict via NamedTuple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
amazing little snippet to convert dictionary into dot notation object | |
""" | |
from collections import namedtuple | |
import json | |
# original dictionary | |
goober = {'zebra': True, 'tronic': {'important_number': 42}} | |
# convert to obj | |
goober_obj = json.loads(json.dumps(goober), object_hook=lambda d: namedtuple("GooberObj", d.keys())(*d.values())) | |
# usage, even with tab completion! | |
""" | |
In [30]: goober_obj.zebra | |
Out[30]: True | |
In [32]: goober_obj.tronic | |
Out[32]: GooberObj(important_number=42) | |
In [33]: goober_obj.tronic.important_number | |
Out[33]: 42 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very nice!