
Untitled
By: a guest on
Jun 27th, 2012 | syntax:
None | size: 2.75 KB | hits: 7 | expires: Never
Complex transforming nested dictionaries into objects in python
combination = {
'item1': 3.14,
'item2': 42,
'items': [
'text text text',
{
'field1': 'a',
'field2': 'b',
},
{
'field1': 'c',
'field2': 'd',
},
]
}
def function(combination):
...
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
class ComboParser(object):
def __init__(self,data):
self.data=data
def __getattr__(self,key):
try:
return ComboParser(self.data[key])
except TypeError:
result=[]
for item in self.data:
if key in item:
try:
result.append(item[key])
except TypeError: pass
return ComboParser(result)
def __getitem__(self,key):
return ComboParser(self.data[key])
def __iter__(self):
if isinstance(self.data,basestring):
# self.data might be a str or unicode object
yield self.data
else:
# self.data might be a list or tuple
try:
for item in self.data:
yield item
except TypeError:
# self.data might be an int or float
yield self.data
def __length_hint__(self):
return len(self.data)
combination = {
'item1': 3.14,
'item2': 42,
'items': [
'text text text',
{
'field1': 'a',
'field2': 'b',
},
{
'field1': 'c',
'field2': 'd',
},
{
'field1': 'e',
'field3': 'f',
},
]
}
print(list(ComboParser(combination).item1))
# [3.1400000000000001]
print(list(ComboParser(combination).items))
# ['text text text', {'field2': 'b', 'field1': 'a'}, {'field2': 'd', 'field1': 'c'}, {'field3': 'f', 'field1': 'e'}]
print(list(ComboParser(combination).items[0]))
# ['text text text']
print(list(ComboParser(combination).items.field1))
# ['a', 'c', 'e']
import types
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
for k,v in self.__dict__.items():
if type(v) == types.DictType:
setattr(self, k, Struct(**v))
>>> b = Struct(a=1, b={'a':1})
>>> b.b.a
1
class Struct:
def __init__(self, **entries):
for key, value in entries.iteritems():
value2 = (Struct(**value) if isinstance(value, dict) else value)
self.__dict__[key] = value2
entries = {
"a": 1,
"b": {
"c": {
"d": 2
}
}
}
obj = Struct(**entries)
print(obj.a) #1
print(obj.b.c.d) #2