0
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.

maxwhere
  • 125
  • 1
  • 9

3 Answers3

1

Simply add a condition inside f string

f"""{d['prefix'] or ''} {d['surname'][0]+'. ' if d['surname'] is not None else ''}{d['name']}"""
chepner
  • 497,756
  • 71
  • 530
  • 681
Nuri Taş
  • 3,828
  • 2
  • 4
  • 22
0

Use condition to check if name has value.

f"""{d['name'][0] if d.get('name') else None}"""
Paul
  • 35
  • 5
0

use if in f-string

f"{d['prefix'] or ''} {d['name'] if d['name'] != None else ''}. {d['surname']}"
Sk4rt
  • 1
  • 1