1

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

3
  • any reason why you're not using str.format notation?
    – jeschwar
    Jun 27, 2019 at 18:33
  • One way: f"{airports['key']}".
    – CristiFati
    Jun 27, 2019 at 18:34
  • With format(): message = '{key}'.format(**airports) Jun 27, 2019 at 18:36

1 Answer 1

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.