OrderedDict with kwds

Albert-Jan Roskam sjeik_appie at hotmail.com
Fri Apr 21 14:08:10 EDT 2017


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?

Below is OrderedDict.__init__. Would the insertion order be preserved if the last line were to be replaced with:

if kwds:
    for k, v in kwds.items():
        self[k] = v
if args:
    self.__update(*args)  # no **kwds!


###
class OrderedDict(dict):
    'Dictionary that remembers insertion order'

    def __init__(*args, **kwds):
        '''Initialize an ordered dictionary.  The signature is the same as
        regular dictionaries, but keyword arguments are not recommended because
        their insertion order is arbitrary.
        '''
        if not args:
            raise TypeError("descriptor '__init__' of 'OrderedDict' object "
                            "needs an argument")
        self, *args = args
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        try:
            self.__root
        except AttributeError:
            self.__hardroot = _Link()
            self.__root = root = _proxy(self.__hardroot)
            root.prev = root.next = root
            self.__map = {}
        self.__update(*args, **kwds)

Thanks!

Albert-Jan


More information about the Python-list mailing list