Key-ordered dict in Python

前端 未结 10 2229
北恋
北恋 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:43

    Here's one option that has not been mentioned in other answers, I think:

    • Use a binary search tree (Treap/AVL/RB) to keep the mapping.
    • Also use a hashmap (aka dictionary) to keep the same mapping (again).

    This will provide O(n) ordered traversal (via the tree), O(1) random access (via the hashmap) and O(log n) insertion/deletion (because you need to update both the tree and the hash).

    The drawback is the need to keep all the data twice, however the alternatives which suggest keeping a list of keys alongside a hashmap are not much better in this sense.

提交回复
热议问题