F format question

I have a small question about f format notation.

This works for me:

print("Sample counts per class:\n{}".format(
      {n: v for n, v in zip(cancer.target_names, np.bincount(cancer.target))}))

But this doesn’t:

print(f"Sample counts per class:\n {n: v for n, v in zip(cancer.target_names, np.bincount(cancer.target))}")

it gives me this error:

Traceback (most recent call last):
  File "C:\Users\User\machinelearn\chapter2.py", line 13, in <module>
    print(f"Sample counts per class:\n {n: v for n, v in zip(cancer.target_names, np.bincount(cancer.target))}")
NameError: name 'n' is not defined

Have been searching the internet for a while to find a solution, but cannot find anything that is comprehensible for me.

edit:

data = {n: v for n, v in zip(cancer.target_names, np.bincount(cancer.target))}
print(f"Sample counts per class:\n {data}")

This works, but is not optimally how I would like to write it.

You’re creating a dict on the fly, right? That means you need to enclose the dict comprehension in curly braces. Which you believe you’re doing already…? :wink:

Aha I see. Thank you!

A free service run by Zed A. Shaw for learncodethehardway.org.