Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

131
Vistas
Dictionary/set comprehensions inside of f-string

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?

10 months ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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?────────────╯ 
10 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos