Check If Parent Dict Is Not Empty And Retrieve The Value Of The Nested Dict
Let's suppose that I have a nested dictionary which looks like that: parent_dict = { 'parent_key': {'child_key': 'child_value'} How can I write the following code: if parent_dict.
Solution 1:
you could use the dict.get
method:
if parent_dict.get('parent_key', {}).get('child_key') == 'value_1':
...
dict.get(key)
will return dict[key]
if the key exists; otherwise it will return None
.dict.get(key, default)
will return default
if the key does not exist. setting the default value to an empty dict {}
will make the second .get
work.
Solution 2:
Use key in dict
:
if 'parent_key' in parent_dict and parent_dict['parent_key']['child_key'] == 'value_1':
print('Value detected')
Post a Comment for "Check If Parent Dict Is Not Empty And Retrieve The Value Of The Nested Dict"