[Python-ideas] f-string, for dictionaries
Steven D'Aprano
steve at pearwood.info
Wed Oct 26 07:29:56 EDT 2016
On Tue, Oct 25, 2016 at 09:11:06PM +0200, Michel Desmoulin wrote:
> We have a syntax to create strings with variables automatically inferred
> from its context:
>
> >>> name = "Guido"
> >>> print(f'Hello {name}')
> Hello Guido
> Similarly, I'd like to suggest a similar feature for building dictionaries:
>
> >>> foo = 1
> >>> bar = 2
> >>> {:bar, :foo}
> {'bar': 1, 'foo', 2}
How often do you do this? Under what circumstances do you do this?
If your code is like my code, the answer is: very rarely; and it is so
long since I've needed anything like this I don't recall why. I don't
think this is a common operation.
So even though writing:
{'spam': spam, 'eggs': eggs}
or even:
dict(spam=spam, eggs=eggs)
is a bit of an annoyance, it doesn't happen often enough to matter, and
its better to just write what you want explicitly rather than have to
learn another special syntax for something you use so rarely you'll
probably never remember it. Or at least, *I'll* never remember it. It
will be just one more cryptic and strange syntax to confuse beginners
and intermediate users with:
# I never remember which one to use...
{:spam, :eggs}
{spam:, eggs:}
{spam, eggs}
> And a similar way to get the content from the dictionary into variables:
>
> >>> values = {'bar': 1, 'foo', 2}
> >>> {:bar, :foo} = values
> >>> bar
> 1
> >>> foo
> 2
Check the archives:
https://mail.python.org/pipermail/python-ideas/2016-May/040430.html
https://mail.python.org/pipermail/python-ideas/2008-March/001511.html
https://mail.python.org/pipermail/python-ideas/2008-April/001513.html
--
Steve
More information about the Python-ideas
mailing list