replace keys in a dictionary python code example
Example 1: python change a key in a dictionary
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]
dictionary[new_key] = dictionary.pop(old_key)
Example 2: replace key of dictionary python
a_dict = {"a": 1, "B": 2, "C": 3}
new_key = "A"
old_key = "a"
a_dict[new_key] = a_dict.pop(old_key)
print(a_dict)
OUTPUT
{'B': 2, 'C': 3, 'A': 1}
Example 3: python replace by dictionary
address = "123 north anywhere street"
for word, initial in {"NORTH":"N", "SOUTH":"S" }.items():
address = address.replace(word.lower(), initial)
print address