update_dict_keys

pyhelpers.ops.update_dict_keys(dictionary, replacements=None)[source]

Update keys in a (nested) dictionary.

See also [OPS-UDK-1] and [OPS-UDK-2].

Parameters:
  • dictionary (dict) – a (nested) dictionary in which certain keys are to be updated

  • replacements (dict | None) – a dictionary in the form of {<current_key>: <new_key>}, describing which keys are to be updated, defaults to None

Returns:

an updated dictionary

Return type:

dict

Examples:

>>> from pyhelpers.ops import update_dict_keys

>>> source_dict = {'a': 1, 'b': 2, 'c': 3}

>>> upd_dict = update_dict_keys(source_dict, replacements=None)
>>> upd_dict  # remain unchanged
{'a': 1, 'b': 2, 'c': 3}

>>> repl_keys = {'a': 'd', 'c': 'e'}
>>> upd_dict = update_dict_keys(source_dict, replacements=repl_keys)
>>> upd_dict
{'d': 1, 'b': 2, 'e': 3}

>>> source_dict = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': {'f': 4, 'g': 5}}}

>>> repl_keys = {'d': 3, 'f': 4}
>>> upd_dict = update_dict_keys(source_dict, replacements=repl_keys)
>>> upd_dict
{'a': 1, 'b': 2, 'c': {3: 3, 'e': {4: 4, 'g': 5}}}