Advertisement
Guest User

Untitled

a guest
Feb 24th, 2015
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3.  
  4.  
  5. import unittest
  6. import itertools
  7. from collections import defaultdict
  8.  
  9.  
  10. def dictmaker():
  11.     return defaultdict(dictmaker)
  12.  
  13.  
  14. def dot_to_dict(dotted):
  15.     r = dictmaker()
  16.     for k, v in dotted.iteritems():
  17.         current = r
  18.         subkeys = k.split('.')
  19.         for sub_k in itertools.islice(subkeys, len(subkeys)-1):
  20.             current = current[sub_k]
  21.         current[subkeys[-1]] = v
  22.     return r
  23.  
  24.  
  25. def dotted_to_dict(incoming):
  26.     """ Because incoming is a list of dicts, and no benefit can be gained from
  27.    doing a global transformation, let's do it dict by dict."""
  28.     return [dot_to_dict(i) for i in incoming]
  29.  
  30.  
  31. class TestDottedToDict(unittest.TestCase):
  32.     def setUp(self):
  33.         self.dotted = [{'a': 1, 'b.e.f': 2, 'b.e.g': 9, 'c.a': 5, 'c.d': 10},
  34.                        {'a': 6, 'b.f.f': 8, 'b.f.g': 0, 'c.a': None,
  35.                         'c.d': 15},
  36.                        ]
  37.  
  38.         self.expected = [{'a': 1, 'b': {'e': {'f': 2, 'g': 9}},
  39.                           'c': {'a': 5, 'd': 10}},
  40.                          {'a': 6, 'b': {'f': {'f': 8, 'g': 0}},
  41.                           'c': {'a': None, 'd': 15}},
  42.                          ]
  43.  
  44.     def testClasses(self):
  45.         """
  46.        """
  47.         got = dotted_to_dict(self.dotted)
  48.         self.assertEquals(got, self.expected)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement