Dictionary/set comprehensions inside of f-string
Asked Answered
E

1

24

Is it possible to have a dictionary or set comprehension inside of an f-string in python 3.6+?

It seems syntactically impossible:

names = ['a', 'b', 'c']
pks = [1, 2, 3]

f"{{name : pk for name, pk in zip(names, pks)}}"

This will return:

{name : pk for name, pk in zip(names, pks)}

This is expected behavior, double brackets result in literal brackets in the output as the expression isn't evaluated.

Has anyone found a workaround to allow for dictionary/set comprehensions inside of f-strings?

Emelia answered 5/3, 2018 at 21:53 Comment(3)
Parentheses, spaces, …Gabfest
@vaultah only the leading space is essential, although the trailing space is nice for symmetry perhapsJola
Spaces and parenthesis seem to work, however ellipsis don't :)Emelia
B
29

Add spaces, they are syntactically required and won’t appear in the resulting string:

>>> names = ['a', 'b', 'c']
>>> pks = [1, 2, 3]
>>> f"{ {name: pk for name, pk in zip(names, pks)} }"
    #  ▲                                          ▲
    #  │                                          │ 
    #  ╰───────────────See the spaces?────────────╯ 
"{'a': 1, 'b': 2, 'c': 3}"
Bel answered 26/12, 2018 at 22:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.