Python Dictionary Help


Assigning a dictionary with three key-value pairs to residents:

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

print residents['Puffin'] # Prints Puffin's room number

Your code here!

print residents['Sloth' and 'Burmese Python']

why does it print 104 and 106 not 105 and 106?


Hi @16dpbstjschools_org ,

The 104 that gets printed is from the statement ...

print residents['Puffin'] # Prints Puffin's room number

Then this statement outputs 106 ...

print residents['Sloth' and 'Burmese Python']

The reason for this may seem a little strange, and is as follows ...
The expression inside the square brackets contains an and, which is a boolean operator. The operands that it operates upon are 'Sloth' and 'Burmese Python'. First the string, 'Sloth', is evaluated. Since it is not an empty string, it is considered to correspond to the boolean value, True. So then, to complete the evaluation of the expression in the square brackets, the Python interpreter needs to determine whether the second operand is a True or a False value. Therefore, it evaluates the string 'Burmese Python'. That also corresponds to a boolean True value, and that becomes the value of the entire expression. So ...

print residents['Sloth' and 'Burmese Python']

... is equivalent to ...

print residents['Burmese Python']

... and 106 gets output.