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

Python get function adds

I was trying to read an example when i stumbled upon a form i couldn’t quite understand:

my_values = parse_qs("red=5&blue=0&green=", keep_blank_values=True)

opacity = my_values.get("opacity", [""])[0] or 0

The code was calling a dict i made and made a parameter for when the value is missing then added "[0] or 0" part to the code which i couldn’t understand how it works

So i tried to run the code asking for a key that wasn’t there to run the parameter and it gave me zero as an answer to my unidentified key

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

when i tried to run the same code without "[0] or 0" part it gave an empty list "[""]" for the unknown key and when i removed the "or 0" part the answer changed to just this ""

So what functionality is this? so i can read more about it?

Thanks in advance

>Solution :

This is an occasional pattern used to handle falsy values and also non-existent keys in a dictionary. For instance,

>>> d1 = {"opacity": ""}
>>> d2 = {"opacity": None}
>>> d3 = {}
>>> d1.get("opacity") or 0
0
>>> d2.get("opacity") or 0
0
>>> d3.get("opacity") or 0
0

All 3 of them give you the same result without throwing a key error.

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