Last active
May 18, 2016 13:43
-
-
Save bofm/1e72760fe00d4f5faa66fd4a2c078c3a to your computer and use it in GitHub Desktop.
Copy item from one dict to another supporting subdicts access using dots in keys
This file contains 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 functools import reduce | |
from contextlib import suppress | |
def copy_key(src_dict, dst_dict, src_key, dst_key): | |
_s, _d = src_dict, dst_dict | |
with suppress(KeyError): | |
if '.' in dst_key: | |
*subkeys, dst_key = dst_key.split('.') | |
dst_dict = reduce(lambda x, y: x.setdefault(y, {}), subkeys, dst_dict) | |
if '.' in src_key: | |
*subkeys, src_key = src_key.split('.') | |
src_dict = reduce(lambda x, y: x[y], subkeys, src_dict) | |
dst_dict[dst_key] = src_dict[src_key] | |
return _s, _d | |
x = copy_key({'a':{'b':2}}, {}, 'a.b', 'a.b.c.d')[1] | |
assert x == {'a':{'b':{'c':{'d':2}}}}, x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment