In Python what is the most efficient way to do this:
my_var = some_var[\'my_key\'] | None
ie. assign some_var[\'my_key\']
to
The great thing about the .get()
method is you can actually define a value to return in case the key doesn't exist.
my_dict = { 1: 'one', 2: 'two' }
print my_dict.get(3, 'Undefined key')
would print.
Undefined key
This is very helpful not only for debugging purposes, but also when parsing json (in my experience, at least), and you should prefer using get()
over []
as much as possible.