Search code examples
pythondictionarynonetypef-string

Python f-string parsing NoneType from dictionary


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.


Solution

  • Simply add a condition inside f string

    f"""{d['prefix'] or ''} {d['surname'][0]+'. ' if d['surname'] is not None else ''}{d['name']}"""