Search code examples
pythonf-string

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?


Solution

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