Skip to content

Instantly share code, notes, and snippets.

@bofm
Last active May 18, 2016 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bofm/1e72760fe00d4f5faa66fd4a2c078c3a to your computer and use it in GitHub Desktop.
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
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