Created
July 16, 2014 16:44
-
-
Save joetastic/2922532a9d5d109227c0 to your computer and use it in GitHub Desktop.
A python function for two way dictionary transformations
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
from collections import defaultdict | |
example_map= ( | |
('n.given_name', 'first'), | |
('n.family_name', 'last'), | |
('tel.value', 'tel'), | |
('tel.type', 'teltype') | |
) | |
def transform(source, map_, reverse=False): | |
infinite_defaults = lambda: defaultdict(infinite_defaults) | |
dest = infinite_defaults() | |
for attr in map_: | |
if reverse: | |
from_, to = attr | |
else: | |
to, from_ = attr | |
from_ = from_.split('.') | |
to = to.split('.') | |
def _get(k, ob): | |
if len(k) > 1: | |
return _get(k[1:], ob[k[0]]) | |
else: | |
return ob[k[0]] | |
try: | |
val = _get(from_, source) | |
except KeyError: # if we can't find a key in the source, then we skip it | |
continue | |
def _set(k, ob): | |
if len(k) > 1: | |
_set(k[1:], ob[k[0]]) | |
else: | |
ob[k[0]] = val | |
_set(to, dest) | |
return dest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment