Search code examples
pythondictionaryintegerbooleankey-value

Problem in accessing Dictionary with key as True and Integer key as 1


MyCODE


   mydict={True:'Visa',2:"verified",1:'Married',(111,222):'dept1 office 2'}
   print(f"mydict.get(True)---> {mydict.get(True)}")
   print(f"mydict.get(2)---> {mydict.get(2)}")
   print(f"mydict.get(1)---> {mydict.get(1)}")
   print(f"mydict.get((111,222))---> {mydict.get((111,222))}")

OUTPUT

mydict.get(True)---> Married
mydict.get(2)---> verified
mydict.get(1)---> Married
mydict.get((111,222))---> dept1 office 2

My question is why mydict.get(True)---> Married ...It should be Visa right...why it happened that?


Solution

  • The data type is not a distinguishing factor for hashing of numeric keys in a dictionary.

    The following dictionary:

    {True:'A', 1:'B', 1.0:'C'}
    

    Actually ends up being:

    {True: 'C'}
    

    because the last value updates the initial key when you provide the same key multiple times. So, a value of 1 is considered the same whether it is a boolean, integer or float. This is consistent with comparison operators: True == 1 == 1.0

    If you want the distinction to be made, you'll need to either convert everything to a string or add the data type as part of the key (neither seem very good, so perhaps you'll want to use a different convention for the True key).