[Python-ideas] Dict literal use for custom dict classes

Jelte Fennema me at jeltef.nl
Sat Dec 12 19:13:49 EST 2015


I really like the OrderedDict class. But there is one thing that has always
bothered me about it. Quite often I want to initialize a small ordered
dict. When the keys are all strings this is pretty easy, since you can just
use the keyword arguments. But when  some, or all of the keys are other
things this is an issue. In that case there are two options (as far as I
know). If you want an ordered dict of this form for instance: {1: 'a', 4:
int, 2: (3, 3)}, you would either have to use:
OrderedDict([(1, 'a'), (4, int), (2, (3, 3))])

or you could use:
d = OrderedDict()
d[1] = 'a'
d[4] = int
d[2] = (3, 3)

In my opinion both are quite verbose and the first is pretty unreadable
because of all the nested tuples. That is why I have two suggestions for
language additions that fix that.
The first one is the normal dict literal syntax available to custom dict
classes like this:
OrderedDict{1: 'a', 4: int, 2: (3, 3)}

This looks much cleaner in my opinion. As far as I can tell it could simply
be implemented as if the either of the two above options was used. This
would make it available to all custom dict types that implement the two
options above.

A second very similar option, which might be cleaner and more useful, is to
make this syntax available (only) after initialization. So it could be used
like this:
d = OrderedDict(){1: 'a', 4: int, 2: (3, 3)}
d{3: 4, 'a': 'c'}
*>>> *OrderedDict(){1: 'a', 4: int, 2: (3, 3), 3: 4, 'a': 'c'}

This would allow arguments to the __init__ method as well. And this way it
could simply be a shorthand for setting multiple attributes. It might even
be used to change multiple values in a list if that is a feature that is
wanted.

Lastly I think either of the two sugested options could be used to allow
dict comprehensions for custom dict types. But this might require a bit
more work (although not much I think).

I'm interested to hear what you guys think.

Jelte

PS. I read part of this thread
https://mail.python.org/pipermail/python-ideas/2009-June/thread.html#4916,
but that seemed more about making OrderedDict itself a literal. Which is
not what I'm suggesting here.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151213/bef452e7/attachment.html>


More information about the Python-ideas mailing list