Key-ordered dict in Python

前端 未结 10 2225
北恋
北恋 2020-11-28 05:14

I am looking for a solid implementation of an ordered associative array, that is, an ordered dictionary. I want the ordering in terms of keys, not of insertion order.

10条回答
  •  臣服心动
    2020-11-28 05:46

    The ordereddict package ( http://anthon.home.xs4all.nl/Python/ordereddict/ ) that I implemented back in 2007 includes sorteddict. sorteddict is a KSO ( Key Sorted Order) dictionary. It is implemented in C and very space efficient and several times faster than a pure Python implementation. Downside is that only works with CPython.

    >>> from _ordereddict import sorteddict
    >>> x = sorteddict()
    >>> x[1] = 1.0
    >>> x[3] = 3.3
    >>> x[2] = 2.2
    >>> print x
    sorteddict([(1, 1.0), (2, 2.2), (3, 3.3)])
    >>> for i in x:
    ...    print i, x[i]
    ... 
    1 1.0
    2 2.2
    3 3.3
    >>> 
    

    Sorry for the late reply, maybe this answer can help others find that library.

提交回复
热议问题