0

I want to do the following with less code:

if "address" in structured_data:
    if "addressCountry" in structured_data["address"]:
        data["country"] = structured_data["address"]["addressCountry"]

Is this possible?

martineau
  • 119,623
  • 25
  • 170
  • 301
BigJoe714
  • 6,732
  • 7
  • 46
  • 50
  • 2
    What do you want to happen when a key is not there? – Olivier Melançon Jan 17 '20 at 00:11
  • 3
    Does this answer your question? [Elegant way to check if a nested key exists in a python dict](https://stackoverflow.com/questions/43491287/elegant-way-to-check-if-a-nested-key-exists-in-a-python-dict) – Ismael Padilla Jan 17 '20 at 00:11
  • Do you want to throw an exception if the key isn't there, silently return None, or create a new element (like `defaultdict` does)? Since you have an if-ladder of guard clauses, seems like silently return None (?) – smci Jan 17 '20 at 00:18

1 Answers1

2

What about using a try?

try:
    data["country"] = structured_data['address']['addressCountry']
except KeyError:
    pass # handle what you want to do
marcos
  • 4,473
  • 1
  • 10
  • 24