Alex Deft
Alex Deft

Reputation: 2787

Problem with using dictionaries inside f string

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?

Upvotes: 0

Views: 306

Answers (1)

Mars
Mars

Reputation: 2572

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']

Upvotes: 2

Related Questions