Skip to content

Instantly share code, notes, and snippets.

@sneeu
Created July 24, 2013 14:45
Show Gist options
  • Save sneeu/6071251 to your computer and use it in GitHub Desktop.
Save sneeu/6071251 to your computer and use it in GitHub Desktop.
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