Skip to content

Instantly share code, notes, and snippets.

@gonz
Last active December 20, 2015 03:39
Show Gist options
  • Save gonz/6065551 to your computer and use it in GitHub Desktop.
Save gonz/6065551 to your computer and use it in GitHub Desktop.
Dict mapper
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