[Python-ideas] OrderedDict literals
David Mertz
mertz at gnosis.cx
Wed Mar 19 09:00:51 CET 2014
It doesn't feel to me like the existing (non-literal) spelling is
particularly bad:
>>> o1 = OrderedDict(foo=1, bar=2, baz=3)
>>> o2 = OrderedDict([('foo',1), ('bar',2), ('baz',3)])
>>> o1
OrderedDict([('bar', 2), ('foo', 1), ('baz', 3)])
>>> o2
OrderedDict([('foo', 1), ('bar', 2), ('baz', 3)])
So sure, you can't use the kw=val style of initialization, but the "list of
pairs" style works fine. It's not that much longer than a literal would be.
On Tue, Mar 18, 2014 at 5:54 PM, Anthony Towns <aj at erisian.com.au> wrote:
> Hi,
>
> I was re-reading some old threads about ordereddict literals to see if
> any of them had gotten anywhere. Amongst them, I came across a post by
> Tim Delaney:
>
> https://mail.python.org/pipermail/python-ideas/2011-January/009049.html
>
> that mentioned an odict literal of ['key': 'value', 'key2': 'value2']
> could be confused with slice notation.
>
> From a syntax point-of-view, that doesn't seem to be true (as
> mentioned in some of the replies to that thread), but it seems like
> you can abuse the similarity to make it a little easier to declare
> ordereddicts:
>
> from collections import OrderedDict
> class ODSlicer(object):
> def __getitem__(self, key):
> if type(key) is slice:
> key = [key]
> od = OrderedDict()
> for k in key:
> if type(k) is slice:
> od[k.start] = k.stop
> else:
> od[k] = k
> return od
> od = ODSlicer()
>
> print(od[1:2])
> print(od["a":"b", "c":5])
> print(od['a':'b', 'c':'d', ..., 'a':10, 'e':'f'])
>
>
> You could then replace:
>
> mydict = {
> 'foo': 'bar',
> 'baz': 'quux',
> }
>
> with:
>
> mydict = od[
> 'foo': 'bar',
> 'baz': 'quux',
> ]
>
> if you need to convert a hardcoded dict into a hardcoded ordereddict.
> Works fine in python2.7 and python3.4.
>
>
> At this point, I'd like to note in my defence that this isn't called
> the python-good-ideas list :)
>
> What's the actual objection to supporting ['foo': 'bar'] odict
> literals? I saw Guido gave a -100, way back in the day, but no actual
> explanation for why it was distasteful?
>
> https://mail.python.org/pipermail/python-ideas/2009-June/004924.html
>
> Cheers,
> aj
>
> --
> Anthony Towns <aj at erisian.com.au>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
--
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons. Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140319/430b9bac/attachment.html>
More information about the Python-ideas
mailing list