+ 1
Is it necessary that all dict. keys in Python must be of same type
4 Respuestas
+ 5
keys in python dicts can be any data type, as long as they are immutable. this creates a dict with keys as:
- int
- string
- tuple
- float
dic = {1:'one', 'a':[1,2,3], (1,3):'hello',1.34:'no'}
+ 4
By a simple test using this snippet, it seems keys of different types are acceptable. I think the key's mutability matters more.
d = { "one" : 1, 1 : "True", 2 : "two", 3 : 3, True : 4 }
print(d)
+ 3
Jan Markus
I guess Python only rewrites the value of an item if the item's key can be evaluated as equal to the key of a new item being inserted.
+ 2
#Ipang
Thank u friend😊