-
Notifications
You must be signed in to change notification settings - Fork 2
/
DictDotLookup.py
36 lines (31 loc) · 1.07 KB
/
DictDotLookup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
__version__ = "1.0"
__author__ = "David Moss"
# zmousm: taken from here:
# http://code.activestate.com/recipes/576586-dot-style-nested-lookups-over-dictionary-based-dat/
import pprint
class DictDotLookup(object):
"""
Creates objects that behave much like a dictionaries, but allow nested
key access using object '.' (dot) lookups.
"""
def __init__(self, d):
for k in d:
if isinstance(d[k], dict):
self.__dict__[k] = DictDotLookup(d[k])
elif isinstance(d[k], (list, tuple)):
l = []
for v in d[k]:
if isinstance(v, dict):
l.append(DictDotLookup(v))
else:
l.append(v)
self.__dict__[k] = l
else:
self.__dict__[k] = d[k]
def __getitem__(self, name):
if name in self.__dict__:
return self.__dict__[name]
def __iter__(self):
return iter(self.__dict__.keys())
def __repr__(self):
return pprint.pformat(self.__dict__)