Are keys with the same key value but different key data types treated as identical?



If two keys are used to add items to the dictionary and the two keys have the same values (for the key, not the item), are they treated as identical so that only one addition is made to the dictionary?


No, if the keys are of different types then they are treated as two different keys, so there are two insertions made to the dictionary. Consider the following example code. Two insertions are made to the dictionary, one with a key value of the number 5 and one with a string containing 5. Since they are different data types, they keys are treated as unique and two entries are made in the dictionary. When using keys that may be numeric, it’s important to make sure that the code is consistent in treating them strictly as numbers or always converting them to strings when used as a key so that no duplications such as this can occur.

mydict = { }

mydict[5] = "value1"

mydict['5'] = "value2"

# {5: 'value1', '5': 'value2'}


Many keys can point to one value.

>>> my_dict = { 'key' + str(x+1): 0 for x in range(10) }
>>> my_dict
{'key7': 0, 'key6': 0, 'key3': 0, 'key5': 0, 'key10': 0, 'key9': 0, 'key2': 0, 'key4': 0, 'key8': 0, 'key1': 0}

If we attempt to assign multiple values to the same key, only the last one sticks.

>>> my_dict = { 'key': x for x in range(10) }
>>> my_dict
{'key': 9}

Values of different types constitute different values.