Skip to content

Instantly share code, notes, and snippets.

@pszaflarski
Created July 9, 2018 17:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pszaflarski/b139736415abbf8d344d77524baaece8 to your computer and use it in GitHub Desktop.
Save pszaflarski/b139736415abbf8d344d77524baaece8 to your computer and use it in GitHub Desktop.
remap a python dictionary with new keys
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