Accessing items in an collections.OrderedDict by index

后端 未结 9 1606
我寻月下人不归
我寻月下人不归 2020-11-28 19:41

Lets say I have the following code:

import collections
d = collections.OrderedDict()
d[\'foo\'] = \'python\'
d[\'bar\'] = \'spam\'

Is there

9条回答
  •  醉话见心
    2020-11-28 20:17

    Do you have to use an OrderedDict or do you specifically want a map-like type that's ordered in some way with fast positional indexing? If the latter, then consider one of Python's many sorted dict types (which orders key-value pairs based on key sort order). Some implementations also support fast indexing. For example, the sortedcontainers project has a SortedDict type for just this purpose.

    >>> from sortedcontainers import SortedDict
    >>> sd = SortedDict()
    >>> sd['foo'] = 'python'
    >>> sd['bar'] = 'spam'
    >>> print sd.iloc[0] # Note that 'bar' comes before 'foo' in sort order.
    'bar'
    >>> # If you want the value, then simple do a key lookup:
    >>> print sd[sd.iloc[1]]
    'python'
    

提交回复
热议问题