Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does the dictionary work in this example?

I was working on a simple example on dictionaries in Python, I realized that there was a problem and I didn’t understand it.

paris = {
    1: 'apple',
    'orange': [2, 3, 4],
    True: False,
    12: 'True',
}
print(paris)

Why is my output for this code:

{1: False, 'orange': [2, 3, 4], 12: 'True'} and not {1: 'apple', 'orange': [2, 3, 4], True:False, 12: 'True'}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The value for the key 1 is False, not 'apple', as I expected. If I use another number for key number 1, I get the expected output.

>Solution :

The error is because you have both the keys 1 and True, which resolves to 1. And since in Python dictionaries, the keys have to be unique, the 1:apple gets overwritten by True: False, which gets displayed as 1: False.

Putting boolean values in a dictionary along with other types of variables isn’t a great idea.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading