Note that Python dict returns default value if there is no key

Parameters etc. are handled by dict.

I want to return the default value if there is no parameter definition (key).

val = None # Set default
if 'filename' in config:
    val = config['filename']

Or with one liner

val = config['filename'] if 'filename' in config else None

There is a way to write it, but it is complicated.

use get

I was able to set the default value when there was no key in the second argument of get!

val = config.get('filename', None)

It's easy to understand!

Recommended Posts

Note that Python dict returns default value if there is no key
[Introduction to Udemy Python3 + Application] 37. Techniques for determining that there is no value
There is no switch in python
There is no telnet! At that time
Note that writing like this with ruby is writing like this with python
I want to initialize if the value is empty (python)
Get the value while specifying the default value from dict in Python
In the python dictionary, if a non-existent key is accessed, initialize it with an arbitrary value
How Python __dict__ is used
Note that it supports Python 3
Python will fail if there is a space after the backslash
How to judge that the cross key is input in Python3
python3.9 has new features that no one is paying attention to ...
[Python] Whiten the parts that turn black when there is no data in the Choropleth map of Folium.