Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # encoding: utf-8
- import unittest
- import itertools
- from collections import defaultdict
- def dictmaker():
- return defaultdict(dictmaker)
- def dot_to_dict(dotted):
- r = dictmaker()
- for k, v in dotted.iteritems():
- current = r
- subkeys = k.split('.')
- for sub_k in itertools.islice(subkeys, len(subkeys)-1):
- current = current[sub_k]
- current[subkeys[-1]] = v
- return r
- def dotted_to_dict(incoming):
- """ Because incoming is a list of dicts, and no benefit can be gained from
- doing a global transformation, let's do it dict by dict."""
- return [dot_to_dict(i) for i in incoming]
- class TestDottedToDict(unittest.TestCase):
- def setUp(self):
- self.dotted = [{'a': 1, 'b.e.f': 2, 'b.e.g': 9, 'c.a': 5, 'c.d': 10},
- {'a': 6, 'b.f.f': 8, 'b.f.g': 0, 'c.a': None,
- 'c.d': 15},
- ]
- self.expected = [{'a': 1, 'b': {'e': {'f': 2, 'g': 9}},
- 'c': {'a': 5, 'd': 10}},
- {'a': 6, 'b': {'f': {'f': 8, 'g': 0}},
- 'c': {'a': None, 'd': 15}},
- ]
- def testClasses(self):
- """
- """
- got = dotted_to_dict(self.dotted)
- self.assertEquals(got, self.expected)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement