Last active
August 18, 2016 08:14
-
-
Save judy2k/8edbc5449de048d6600b6aaf37d2552a to your computer and use it in GitHub Desktop.
A handy function for copying properties from one dict to another with optional key mapping. Small amount of code, and well tested.
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 transfer_dict import transfer_dict | |
SOURCE = { | |
'a': 'thing', | |
'key': 'value', | |
} | |
def test_basic(): | |
dest = transfer_dict(SOURCE) | |
assert dest == SOURCE | |
assert dest is not SOURCE | |
def test_merge(): | |
dest = { | |
'b': 'other' | |
} | |
d2 = transfer_dict(SOURCE, dest) | |
assert d2 == { | |
'a': 'thing', | |
'b': 'other', | |
'key': 'value', | |
} | |
assert d2 is dest | |
def test_filter(): | |
dest = transfer_dict(SOURCE, keys=['a']) | |
assert dest == { 'a': 'thing' } | |
def test_mapping(): | |
dest = transfer_dict(SOURCE, keys=[('argh', 'a'), 'key']) | |
assert dest == { | |
'argh': 'thing', | |
'key': 'value', | |
} | |
def test_map_override(): | |
dest = { | |
'argh': 'moo', | |
} | |
transfer_dict(SOURCE, dest, keys=[('argh', 'a'), 'key']) | |
assert dest == { | |
'argh': 'thing', | |
'key': 'value', | |
} |
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
def transfer_dict(src, dest=None, keys=None): | |
''' | |
Copies (and translates if necessary) some pairs from a source dict to a dest dict. | |
src is the dict to copy from | |
dest is the dict to copy to (or creates a new dict if not provided) | |
keys is a list of keys to be copied. If not provided, it defaults to all the keys in src. | |
If a key is a 2-tuple, it should contain (dest_key, src_key) and provides a mapping between the two dicts. | |
''' | |
if keys is None: | |
keys = src.keys() | |
result = {} | |
for k in keys: | |
if isinstance(k, tuple): | |
dest_key, source_key = k | |
else: | |
dest_key, source_key = k, k | |
result[dest_key] = src[source_key] | |
if dest is None: | |
return result | |
else: | |
dest.update(result) | |
return dest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment