Last active
December 20, 2015 03:39
-
-
Save gonz/6065551 to your computer and use it in GitHub Desktop.
Dict mapper
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 get_dot(d, dotkey): | |
"""Get value from a dict-like object with dot notation keys""" | |
try: | |
value = d | |
for key in dotkey.split('.'): | |
value = value.get(key, {}) | |
return value if value else None | |
except AttributeError: | |
return None | |
def map_dicts(keys_mappings, source_dict_list): | |
return [map_dict(keys_mappings, source_dict) | |
for source_dict in source_dict_list] | |
def map_dict(keys_mappings, source_dict): | |
item = {} | |
for keys in keys_mappings: | |
if not isinstance(keys, (tuple, list)): | |
keys = (keys, keys) | |
if isinstance(keys[1], (tuple, list)): | |
val = map_dict(keys[1], source_dict) | |
else: | |
val = get_dot(source_dict, keys[1]) | |
item[keys[0]] = val | |
return item |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment