python - Use A Conditional Statement To Check If A JSON Key Exists - Python3 -
i able return value of key class
every time rappers in json structure. did parse_classes
function seen below.
how can make conditional statment (if, else, or maybe loop) check if key class
exists in argument json_data
. if exist (the "if") run block of code , if not exists (the "else") move on funcction.
here code:
def parse_classes(json_data): lst = list() #list of values of key "class" found classes in json_data['images'][0]['classifiers'][0]: #runs every time find "classes" exists in json data. item in json_data['images'][0]['classifiers'][0]['classes']: #gets "classes" in json , puts item lst.append(item['class') #adds key "class" "item" list "lst" return(lst) #returns list "lst"
here example json structure:
{"images": ["classifiers": ["classes": ["class": "street"]]]}
thanks, brendan (python 3.6.1, windows 10 64bit)
i think mean if
instead of for
:
def parse_classes(json_data): lst = set() if 'classes' in json_data['images'][0]['classifiers'][0]: item in json_data['images'][0]['classifiers'][0]['classes']: lst.add(item['class']) else: print("") return lst
or defensively
def parse_classes(json_data): lst = set() if (json_data.get('images') , json_data['images'][0].get('classifiers') , json_data['images'][0]['classifiers'][0].get('classes')): item in json_data['images'][0]['classifiers'][0].get('classes', []): lst.add(item['class']) return lst if lst else none
if want class
in classifiers
in images
def parse_classes(json_data): lst = set() image in json_data.get('images', []): classifier in image.get('classifiers', []): item in classifier.get('classes', []): lst.add(item['class']) return lst if lst else none
Comments
Post a Comment