Skip to content

Instantly share code, notes, and snippets.

@ghukill
Created August 16, 2020 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghukill/3c0d841222cfe8995d421017b911243e to your computer and use it in GitHub Desktop.
Save ghukill/3c0d841222cfe8995d421017b911243e to your computer and use it in GitHub Desktop.
dot notation object from python dict via NamedTuple
"""
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
"""
@horizon365
Copy link

very nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment