[Python-ideas] A sorted version of **kwargs

Steven D'Aprano steve at pearwood.info
Fri Jan 21 04:42:13 CET 2011

Hongbao Chen wrote:
> Hey, guys
> I must argue that make **kwargs sorted is really a terrible idea.
> Please think that when user wants a unsorted **kwargs, how can he or she
> bring the original unsorted dict back?

Despite the subject line, this is not about a *sorted* dict, but about
an *ordered* dict. The difference is that an ordered dict remembers the
order that elements are given:

>>> pairs = list(zip('cat', (1,2,3)))
>>> pairs
[('c', 1), ('a', 2), ('t', 3)]
>>> dict(pairs)  # order is lost
{'a': 2, 'c': 1, 't': 3}
>>> from collections import OrderedDict as odict
>>> odict(pairs)  # but ordered dicts keep it
OrderedDict([('c', 1), ('a', 2), ('t', 3)])

The problem is that keyword args are collected in an ordinary
dictionary, which is unordered, so you lose the original order (except
by accident):

>>> odict(c=1, a=2, t=3)
OrderedDict([('a', 2), ('c', 1), ('t', 3)])

So there is currently no way for functions to have arbitrary keyword
arguments supplied in the order in which they were passed, because the
order is lost when they are collected in a dict.


More information about the Python-ideas mailing list