I am thinking about an elegant way of obtaining all the parameters I need. They are located in a text file. I usually read them into a dictionary (like "parameter1":10; "parameter2":20). But I usually do not need all the parameter, eg in some case I don't need to set "parameter1" in the text file. I have 2 ways of doing it: 1) always set all the parameters in the text. If I don't need any one, set it to 0. 2) check if the parameter is available in the dictionary like:
try p1 = dict1.get("parameter1"):
except:
p1 = 0
Same process can be done if I need the parameter but forget to set. The code can set it to a default value. In case of 100 parameters, what I am doing is to repeat this "try, except 100 times" which is not so elegant. I wonder if there is any better choice? The method can be totally different which I don't care since it is just a small step of initializing parameters.
Thanks.
You can use the second parameter in get
to specify a default value if the key is not found
d = {"parameter1":10, "parameter2":20}
>>> d.get('parameter1', 100) # Key exists, will retrieve the value
10
>>> d.get('parameter3', 100) # Key does not exist, retrieves default value
100
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.