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

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', 'tuple')
print(letters)
# {'A': 10, 'B': ('this', 'is', 'a', 'tuple'), 'C': 30, 'D': 40}
8 Likes

Typo. It’s a tuple of strings.

5 Likes

Indeed, it is a tuple. We can verify that by adding this line of code at the end:

print(type(letters["B"]))

Output from that statement:

<class 'tuple'>
5 Likes