Python dictionary - binary search for a key?

后端 未结 5 1323
长发绾君心
长发绾君心 2021-02-05 19:16

I want to write a container class that acts like a dictionary (actually derives from a dict), The keys for this structure will be dates.

When a key (i.e. date) is used t

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-05 19:49

    The sortedcontainers module provides a SortedDict type that maintains the keys in sorted order and supports bisecting on those keys. The module is pure-Python and fast-as-C implementations with 100% test coverage and hours of stress.

    For example:

    from sortedcontainers import SortedDict
    
    sd = SortedDict((date, value) for date, value in data)
    
    # Bisect for the index of the desired key.
    index = sd.bisect('2001/01/05')
    
    # Lookup the real key at that index.
    key = sd.iloc[index]
    
    # Retrieve the value associated with that key.
    value = sd[key]
    

    Because SortedDict supports fast indexing, it's easy to look ahead or behind your key as well. SortedDict is also a MutableMapping so it should work nicely in your type system.

提交回复
热议问题