Python Safely Navigate a Complex Data Structure: Difference between revisions
Jump to navigation
Jump to search
Line 8: | Line 8: | ||
yaml = ... | yaml = ... | ||
v = None | v = None | ||
first_level_map = yaml.get('first_level_key', {}) | first_level_map = yaml.get('first_level_key', {}) # if 'first_level_key' does not exist at all, return {}, but if it exists and has nothing under it, it returns None. | ||
if first_level_map: | if first_level_map: | ||
second_level_map = first_level_map.get('second_level_key', {}) | second_level_map = first_level_map.get('second_level_key', {}) |
Revision as of 00:17, 3 March 2022
Internal
Overview
yaml = ...
v = None
first_level_map = yaml.get('first_level_key', {}) # if 'first_level_key' does not exist at all, return {}, but if it exists and has nothing under it, it returns None.
if first_level_map:
second_level_map = first_level_map.get('second_level_key', {})
if second_level_map:
v = second_level_map.get('leaf_key')
return v