Is it necessary that all dict. keys in Python must be of same type | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Is it necessary that all dict. keys in Python must be of same type

31st Aug 2020, 5:29 AM
Aman[#Wizard]
Aman[#Wizard] - avatar
4 Answers
+ 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'}
31st Aug 2020, 10:55 AM
Lothar
Lothar - avatar
+ 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)
31st Aug 2020, 5:43 AM
Ipang
+ 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.
31st Aug 2020, 6:37 AM
Ipang
+ 2
#Ipang Thank u friend😊
31st Aug 2020, 5:46 AM
Aman[#Wizard]
Aman[#Wizard] - avatar