Search code examples
pythondictionaryf-string

Pycharm keeps saying there is an unmatched [ in an f-string, but it is matched


for a class I'm trying to write a python program. One of the lines tries to use an f string to report the value of a key ('cost') inside of a dictionary ('espresso') that is inside another dictionary ('MENU'). Unfortunately I keep getting:

print(f'That drink costs {MENU["espresso"['cost']]}.')
                                           ^

SyntaxError: f-string: unmatched '['

The line of code that is throwing this error is as follows:

print(f'That drink costs {MENU["espresso"['cost']]}.')

I'm using Pycharm with Python 3.9.

I thought I understood the basic issue here; pycharm/python is for some reason not built to understand that single and double quotes inside the curly braces of an f-string are not actually the end of the print statement, so it would end the print statement and see the rest of the line as a jumble of characters, and throw a syntax error about them.
However if that were the case, it should be seeing the ']' as unmatched, not the '[' that I expected it to think is inside the print quotes and thus not required to be matched. But it objects to the bracket that should be seen as inside the single quotes and fine to print either way. I also see that I am trying to use single quotes for the 'cost' key inside the single quotes of the print statement, but I have to use double quotes for the "espresso" key of the first dictionary. I'm not aware of any third way to show that I am indicating a key of a dictionary. Is it impossible to reference a value inside a nested dictionary in an f string?


Solution

  • That access to the dictionary won't work, even outside f-strings. You are indexing into the string (!) "espresso" with the index "cost".

    There are two problems with your code:

    1. Just index into the outer dictionary, then index into the inner dictionary. Do not nest the square brackets.
    2. Inside ", you can only use ' and vice-versa. (This changes with f-strings in Python 3.12)
    MENU = dict()
    MENU["espresso"] = dict()
    MENU["espresso"]["cost"] = 17.50
    print(MENU['espresso']['cost'])         # without f-string
    print(f"{MENU['espresso']['cost']}")    # with f-string
    print(f'{MENU["espresso"]["cost"]}')    # vice-versa f-string