update_dict_keys¶
- pyhelpers.ops.update_dict_keys(dictionary, replacements=None)[source]¶
Update keys in a (nested) dictionary based on a given replacements dictionary.
See also [OPS-UDK-1] and [OPS-UDK-2].
- Parameters:
dictionary (dict) – The (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 toNone
.
- Returns:
The dictionary with updated keys.
- 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}}}