0
array = {"key1":{"key2":"value"}}

if 'key1' in array:
    if 'key2' in array['key1']:
        print(array['key1']['key2'])
    else
        print(0)

In php it is like this if(isset(array[key1][key2])).

martineau
  • 119,623
  • 25
  • 170
  • 301
Ivan_Aka
  • 23
  • 4

2 Answers2

5

Use in to the dict value of array['key1']

if 'key1' in array and 'key2' in array['key1']:

This is equivalent to the explicit form:

if 'key1' in array.keys() and 'key2' in array['key1'].keys():

A side note, if you're only interested in the value, you might want to look at dict.get() which returns the value of the key if present and returns None if not present (unless you set the default argument which would be the one returned instead).

2

You can use .get():

>>> array.get("key1", {}).get("key2", 0)
not_speshal
  • 22,093
  • 2
  • 15
  • 30