Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 27th, 2012  |  syntax: None  |  size: 2.75 KB  |  hits: 7  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Complex transforming nested dictionaries into objects in python
  2. combination = {
  3. 'item1': 3.14,
  4. 'item2': 42,
  5. 'items': [
  6.          'text text text',
  7.          {
  8.              'field1': 'a',
  9.              'field2': 'b',
  10.          },
  11.          {
  12.              'field1': 'c',
  13.              'field2': 'd',
  14.          },
  15.          ]
  16. }
  17.  
  18. def function(combination):
  19.     ...
  20.        
  21. class Struct:
  22.     def __init__(self, **entries):
  23.         self.__dict__.update(entries)
  24.        
  25. class ComboParser(object):
  26.     def __init__(self,data):
  27.         self.data=data
  28.     def __getattr__(self,key):
  29.         try:
  30.             return ComboParser(self.data[key])
  31.         except TypeError:
  32.             result=[]
  33.             for item in self.data:
  34.                 if key in item:
  35.                     try:
  36.                         result.append(item[key])
  37.                     except TypeError: pass
  38.             return ComboParser(result)
  39.     def __getitem__(self,key):
  40.         return ComboParser(self.data[key])
  41.     def __iter__(self):
  42.         if isinstance(self.data,basestring):
  43.             # self.data might be a str or unicode object
  44.             yield self.data
  45.         else:
  46.             # self.data might be a list or tuple
  47.             try:
  48.                 for item in self.data:
  49.                     yield item
  50.             except TypeError:
  51.                 # self.data might be an int or float
  52.                 yield self.data
  53.     def __length_hint__(self):
  54.         return len(self.data)
  55.        
  56. combination = {
  57.     'item1': 3.14,
  58.     'item2': 42,
  59.     'items': [
  60.         'text text text',
  61.         {
  62.             'field1': 'a',
  63.             'field2': 'b',
  64.             },
  65.         {
  66.             'field1': 'c',
  67.             'field2': 'd',
  68.             },
  69.         {
  70.             'field1': 'e',
  71.             'field3': 'f',
  72.             },        
  73.         ]
  74.     }
  75. print(list(ComboParser(combination).item1))
  76. # [3.1400000000000001]
  77. print(list(ComboParser(combination).items))
  78. # ['text text text', {'field2': 'b', 'field1': 'a'}, {'field2': 'd', 'field1': 'c'}, {'field3': 'f', 'field1': 'e'}]
  79. print(list(ComboParser(combination).items[0]))
  80. # ['text text text']
  81. print(list(ComboParser(combination).items.field1))
  82. # ['a', 'c', 'e']
  83.        
  84. import types
  85. class Struct:
  86.     def __init__(self, **entries):
  87.         self.__dict__.update(entries)
  88.         for k,v in self.__dict__.items():
  89.             if type(v) == types.DictType:
  90.                 setattr(self, k, Struct(**v))
  91.        
  92. >>> b = Struct(a=1, b={'a':1})
  93. >>> b.b.a
  94. 1
  95.        
  96. class Struct:
  97.     def __init__(self, **entries):
  98.         for key, value in entries.iteritems():
  99.             value2 = (Struct(**value) if isinstance(value, dict) else value)
  100.             self.__dict__[key] = value2
  101.  
  102. entries = {
  103.     "a": 1,
  104.     "b": {
  105.         "c": {
  106.             "d": 2
  107.         }
  108.     }
  109. }
  110.  
  111. obj = Struct(**entries)
  112. print(obj.a) #1
  113. print(obj.b.c.d) #2