Skip to content

Instantly share code, notes, and snippets.

@jaekookang
Last active February 17, 2022 01:20
Show Gist options
  • Save jaekookang/2842fbd4e5e89102364082ffc61ca8ea to your computer and use it in GitHub Desktop.
Save jaekookang/2842fbd4e5e89102364082ffc61ca8ea to your computer and use it in GitHub Desktop.
class DotDict(dict):
"""
a dictionary that supports dot notation
as well as dictionary access notation
useful when using it with TensorFlow or PyTorch
Usage:
d = DotDict() or d = DotDict({'val1':'first'})
set attributes: d.val2 = 'second' or d['val2'] = 'second'
get attributes: d.val2 or d['val2']
import json
with open('params.json', 'r') as f:
params = json.load(f)
hp = HParams(params)
with open('new.json', 'w') as f:
json.dump(hp, f, indent=6)
See: https://stackoverflow.com/a/13520518/7170059
2021-04-18 first created
2022-01-12 edited
"""
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def __init__(self, dct):
for key, value in dct.items():
if hasattr(value, 'keys'):
value = DotDict(value)
self[key] = value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment