On 2023-01-27 21:43:09 +0100, Johannes Bauer wrote: > x = { "y": "z" } > s = "-> {x['y']}" > print(s.format(x = x)) > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > KeyError: "'y'" > > This. Does. Not. Work. > > I want to pass a single variable as a dictionary and access its members > inside the expression.
You can do that (see other responses), but you can't have arbitrary Python expressions inside a format string. It works with f-strings because f-strings are a compiler construct. The f-string never exists at run-time. Instead the compiler transforms f"-> {x['y']}" into the equivalent of "-> " + format_value(x["y"]) + "" So either you need to pass it to the Python compiler (via eval), or you need to implement enough of a Python parser/interpreter to cover the cases you are interested in. The latter might be an interesting exercise, but I would suggest looking at existing template engines like Jinja2 for production purposes. hp -- _ | Peter J. Holzer | Story must make more sense than reality. |_|_) | | | | | h...@hjp.at | -- Charles Stross, "Creative writing __/ | http://www.hjp.at/ | challenge!"
signature.asc
Description: PGP signature
-- https://mail.python.org/mailman/listinfo/python-list