0

I'm using f string format to do some printing. The interpreter throws a syntax error when I use a value from a dictionary.

print(f'value = {mydict['key']}')

Why is that, how can I overcome it?

Granny Aching
  • 1,295
  • 12
  • 37
Alex Deft
  • 2,531
  • 1
  • 19
  • 34
  • 1
    Try `print(f"value = {mydict['key']}")` – Arkistarvh Kltzuonstev Jun 09 '19 at 01:12
  • 1
    The f-string ends at the second apostrophe, and the rest of the line, `key']}')`, isn't valid. – kindall Jun 09 '19 at 01:12
  • The double quotation mark trick didn't work. I tried it both ways. Yes I understand whats happening. But this is frustrating cause f-string has been my favourite formatting way. – Alex Deft Jun 09 '19 at 01:14
  • Are there any other lines of codes that you are running? What's the exact error that is thrown? Using the double quote `"` and single quote `'` should work fine. – busybear Jun 09 '19 at 01:31

1 Answers1

2

This works just fine. Make sure you're separating your use of single and double quotes! (If the outer quotes are double quotes, make the quotes around "key" single quotes, or vice-versa)

mydict["key"] = 5   
print(f"value = {mydict['key']}")

value = 5


Followup for OP's comment:
Printing a list isn't a problem either!

mydict["key"] = ["test1", "test2"]   
print(f"value = {mydict['key']}")

value = ['test1', 'test2']

Mars
  • 2,505
  • 17
  • 26
  • I'm trying it. Not working print(f"Epoch={epoch} , Batch={step:2d}/{num_batches:2d}, DC Accuracy={dc_metric.result().numpy():1.3f}, " f"LP Loss={hist['lp_loss_sou']:1.5f}", end='\r') Error:TypeError: unsupported format string passed to list.__format__ – Alex Deft Jun 09 '19 at 01:36
  • It worked! My dictionary was returning a list causing troubles. I specified one entry of that list and it worked. Thanks – Alex Deft Jun 09 '19 at 01:52
  • @AlexDeft A list works as well, so I suspect something else is the issue... – Mars Jun 09 '19 at 02:09
  • No it doesn't work! Well, it worked for you because you never specified the format. But in my case I did this: {mydict["key"]:2d} Notice the :2d. This doesn't work for lists. That's why on my end it didn't work when the dictionary returned a list. – Alex Deft Jun 09 '19 at 02:20
  • Thats a different issue from the syntax error you mentioned in the question :) – Mars Jun 09 '19 at 02:25
  • 1
    @AlexDeft PS, in the future, you should always try to include the actual code and the actual error message! – Mars Jun 09 '19 at 02:25