d = {'surname':"Doe",'name':"Jane",'prefix':"Dr."}
f"""{d['prefix'] or ''} {d['name'][0] '. ' or ''}{d['surname']}"""
works, however
d = {'surname':"Doe",'name':None,'prefix':"Dr."}
f"""{d['prefix'] or ''} {d['name'][0] '. ' or ''}{d['surname']}"""
does not of course. How can I parse values from a dictionary conditionally? Or are there other work-arounds? I am iterating through a list of dictionaries with a lot of entries each so editing the data beforehand is not really an option here.
CodePudding user response:
Simply add a condition inside f string
f"""{d['prefix'] or ''} {d['surname'][0] '. ' if d['surname'] is not None else ''}{d['name']}"""
CodePudding user response:
Use condition to check if name
has value.
f"""{d['name'][0] if d.get('name') else None}"""
CodePudding user response:
use if
in f-string
f"{d['prefix'] or ''} {d['name'] if d['name'] != None else ''}. {d['surname']}"