Created
October 4, 2021 15:46
-
-
Save matthewpoer/1c720ad446825a1a30767f1f00756820 to your computer and use it in GitHub Desktop.
The safest `get()` method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bugs = { | |
"FirstName": "Bugs", | |
"LastName": "Bunny", | |
"Hometown": { | |
"City": "Los Angeles", | |
"State": "California", | |
"Country": { | |
"ISO": "US", | |
"Text": "United States", | |
}, | |
}, | |
} | |
elmer = { | |
"FirstName": "Elmer", | |
"LastName": "Fudd", | |
} | |
daffy = { | |
"FirstName": "Daffy", | |
"LastName": "Duck", | |
"Hometown": None, | |
} | |
character_list = [bugs, elmer, daffy] | |
for character in character_list: | |
print( "LastName: " + character.get("LastName", "") ) | |
# LastName: Bunny | |
# LastName: Fudd | |
# LastName: Duck | |
for character in character_list: | |
hometown = character.get("Hometown") or {} | |
country = hometown.get("Country") or {} | |
country_iso = country.get("ISO") or "" | |
print( "Hometown -> Country -> ISO: " + country_iso ) | |
# Hometown -> Country -> ISO: US | |
# Hometown -> Country -> ISO: | |
# Hometown -> Country -> ISO: | |
for character in character_list: | |
country_iso = character.get("Hometown", {}).get("Country", {}).get("ISO", "") | |
print( "Hometown -> Country -> ISO: " + country_iso ) | |
# Hometown -> Country -> ISO: US | |
# Hometown -> Country -> ISO: | |
# Traceback (most recent call last): | |
# File "<stdin>", line 2, in <module> | |
# AttributeError: 'NoneType' object has no attribute 'get' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment