Search code examples
pythonstring-interpolationf-string

How to include a dict comprehension in an f-string?


Is there any way to use dict comprehension inside a fstring? THe case is the following:

a = ['a', 'b', 'c', 'd']
list_comprehension = [v for v in a]
my_f_string = f"dict comprehension {v:None for v in a}"

I do not wanna use format interpolation ("{}".format(dict_comprehension)). I want to use the most pythonic way to include that list comprehension inside the fstring to be used for logging data.


Solution

  • Yes, of course there is. You simply need to wrap the comprehension in parenthesis ( ), since two consecutive {s are interpreted as a literal "{" string.

    a = ['a', 'b', 'c', 'd']
    list_comprehension = [v for v in a]
    

    This works:

    my_f_string = f"dict comprehension {({v:None for v in a})}"
    print(my_f_string)
    

    Output:

    dict comprehension {'a': None, 'b': None, 'c': None, 'd': None}
    

    But, this does not work (Stack Overflow's syntax highlighting also helpfully shows that):

    my_f_string = f"dict comprehension {{v:None for v in a}}"
    print(my_f_string)
    

    Output:

    dict comprehension {v:None for v in a}