Pandas dataframe to dictionary with conditions

Solution 1:

Use dict comprehension with if condition:

desired_output = {a: {b:c} if pd.notna(b) else c  for a, b,c in df.to_numpy()}
print (desired_output)
{'A': 'S1', 'B': {'P1': 'S2'}, 'C': {'P2': 'S3'}, 'D': 'S4'}