Search code examples
pythonstring-formatting

Injecting the Value of Dictionary into print formatting


How can I inject a value of a dictionary into a string using string interpolation in Python?

airports = {"key":"value"} 
message = f"{airports["key"]}" // this gives a syntax error 

Using Python 3.7


Solution

  • You need to use single quotes for strings,

    airports = {"key":"value"} 
    message = f'{airports["key"]}'
    

    Another way to achieve this is,

    airports = {"key":"value"}
    valToPrint = airports["key"]
    message = f'{valToPrint}'