Created
July 24, 2013 14:45
-
-
Save sneeu/6071251 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def dict_path(from_object, path): | |
""" | |
>>> dict_path({'a': {'b': {'c': 123}}}, ['a', 'b']) | |
{'c': 123} | |
""" | |
if path == []: | |
return from_object | |
return dict_path(from_object[path[0]], path[1:]) | |
def map_attributes(from_object, attribute_map): | |
""" | |
>>> d = map_attributes({'a': {'b': {'c': 123}}}, {'a': 'a', 'b': 'a.b', 'c': 'a.b.c'}) | |
>>> d == {'a': {'b': {'c': 123}}, 'b': {'c': 123}, 'c': 123} | |
True | |
""" | |
r = {} | |
for attr, key in attribute_map.items(): | |
key_path = key.split('.') | |
r[attr] = dict_path(from_object, key_path) | |
return r | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment