Accessing items in an collections.OrderedDict by index

后端 未结 9 1605
我寻月下人不归
我寻月下人不归 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:25

    If you have pandas installed, you can convert the ordered dict to a pandas Series. This will allow random access to the dictionary elements.

    >>> import collections
    >>> import pandas as pd
    >>> d = collections.OrderedDict()
    >>> d['foo'] = 'python'
    >>> d['bar'] = 'spam'
    
    >>> s = pd.Series(d)
    
    >>> s['bar']
    spam
    >>> s.iloc[1]
    spam
    >>> s.index[1]
    bar
    

提交回复
热议问题