I have a question. What will the following code print?
>>> m = {"key": "value"}
>>> f"{m['key']}"
>>> f"{m[key]}"
>>> "{m['key']}".format(m=m)
>>> "{m[key]}".format(m=m)
The f-string
example makes perfect sense to me. It will print the correct value in the first line and raise a NameError
in the second:
>>> f"{m['key']}"
'value'
>>> f"{m[key]}"
NameError: name 'key' is not defined
What about the format string:
>>> "{m['key']}".format(m=m)
KeyError: "'key'"
>>> "{m[key]}".format(m=m)
value
In this case, the first line, that looks like a dictionary access with __getitem__, will raise a KeyError
, while the second line will print the value correctly, but many would say that it should raise a NameError
. This feels very counterintuitive.
By reading the Format String Syntax I understand that element_index
should not be surrounded by quotes.
Iām curious to understand a little bit more about this so Iād like to ask the following questions:
- Does anyone knows why was decided to not use quotes when accessing dictionary values in Format String Syntax? This choice seems to be more difficult to implement than the f-string and also limits the use of closing square brackets.
- Is there any plans to update this syntax? I think that the f-string version is more coherent.
- Iāve had difficulties finding any resources explaining that dictionary access in Format String Syntax should be made without quotes. Itās not explained in the official documentation and almost every other article just expands the dictionaries with
**mapping
. Is there any interest of making this more clear in the documentation?