OrderedDict with kwds

Peter Otten __peter__ at web.de
Sat Apr 22 04:21:28 EDT 2017


Albert-Jan Roskam wrote:

> For regular dicts I like to use the dict() function because the code is
> easier to write and read. But OrderedDict() is not equivalent to dict():
> In the docstring of collections.OrderedDict it says "keyword arguments are
> not recommended because their insertion order is arbitrary"
> (https://github.com/python/cpython/blob/3.6/Lib/collections/__init__.py)
> 
> It took me while to realize that. What is the best way to use keywords to
> create an ordered dict, while maintaining insertion order?

That's the equivalent to "How can I eat my cake and have it." Once you pass 
keyword arguments order is inevitably lost

$ python3 -c 'f = lambda **kw: list(kw); print(f(a=1, b=2))'
['a', 'b']
$ python3 -c 'f = lambda **kw: list(kw); print(f(a=1, b=2))'
['a', 'b']
$ python3 -c 'f = lambda **kw: list(kw); print(f(a=1, b=2))'
['b', 'a']

in all Python versions prior to 3.6. 

However, in 3.6 dict keys stay in insertion order, so you don't even need an 
OrderedDict anymore. Specifically

https://docs.python.org/dev/whatsnew/3.6.html

"""
CPython implementation improvements:
...
The order of elements in **kwargs now corresponds to the order in which 
keyword arguments were passed to the function.
"""




More information about the Python-list mailing list