Can the data type of a value be changed when overwriting it in a dictionary?


#1

Question

Once a value is added to a dictionary when it is overwritten, can the data type for the value be changed?

Answer

Yes, whenever a value is overwritten in a dictionary, it can be saved as another data type regardless of how it was originally stored. In the following code example, the value for key “B” is originally a number. It is then overwritten with a string value and finally a list of strings. All are stored as valid values for key “B”.

letters = { "A": 10, "B": 20, "C": 30, "D": 40 }

letters["B"] = "string"
print(letters)
# {'A': 10, 'B': 'string', 'C': 30, 'D': 40}

letters["B"] = ("this", "is", "a", "list")
print(letters)
# {'A': 10, 'B': ('this', 'is', 'a', 'list'), 'C': 30, 'D': 40}