[Python-ideas] OrderedDict literals
Anthony Towns
aj at erisian.com.au
Wed Mar 19 01:54:54 CET 2014
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>
More information about the Python-ideas
mailing list