Created
July 9, 2018 17:49
-
-
Save pszaflarski/b139736415abbf8d344d77524baaece8 to your computer and use it in GitHub Desktop.
remap a python dictionary with new keys
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
def _remap_dict(d, fromto_mapping, method='delete'): | |
""" | |
Remap dictionary keys from a certain set of keys to a new set of keys | |
:param d: the dictionary that needs to be remapped | |
:param fromto_mapping: a dictionary mapping of keys in the original dictionary to the output dictionary | |
:param method: what do do with keys that aren't found in the mapping | |
'delete' means that they will be removed from the output dictionary | |
'remain' means that they will have their original names in the output dictionary | |
:return: the output dictionary with keys remapped, will return None if method is not recognized | |
""" | |
if method == 'delete': | |
output_dict = {fromto_mapping.get(k, k): v for k, v in d.items() if k in fromto_mapping} | |
elif method == 'remain': | |
output_dict = {fromto_mapping.get(k, k): v for k, v in d.items()} | |
else: | |
output_dict = None | |
return output_dict |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment