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
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.