0

Let's assume we have a dictionary with two keys and known values:

dictionary = {'first_name': 'Jennifer', 'last_name': 'Lawrence'}

However, since I retrieve the information from an API that cannot guarantee that all keys are returned, I have to test whether the keys exist.

If I want to assign the value of this key "first_name" to the variable new_object, I intended to use the following expression:

new_object = dictionary['first_name'] **or None**

However, if the key 'first_name' is not in the dictionary, I receive a key error. Apparently, it seems that I cannot use Swift's principle of optionals here.

Does Python support any kind of inline test to verify that a variable exists/is declared, and if it doesn't instead assigns the value None to the new variable? In the case above, with a dictionary with only the key 'last_name' would, therefore, result in the assignment of the value None to new_object.

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

1

Python dictionaries have a method .get() for this:

new_object = dictionary.get('first_name')

It takes a key and returns either the value (if set) or a default value (which unless otherwise specified is None).

Amber
  • 507,862
  • 82
  • 626
  • 550