Accessing items in an collections.OrderedDict by index

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

    for OrderedDict() you can access the elements by indexing by getting the tuples of (key,value) pairs as follows or using '.values()'

    >>> import collections
    >>> d = collections.OrderedDict()
    >>> d['foo'] = 'python'
    >>> d['bar'] = 'spam'
    >>> d.items()
    [('foo', 'python'), ('bar', 'spam')]
    >>>d.values()
    odict_values(['python','spam'])
    >>>list(d.values())
    ['python','spam']
    

提交回复
热议问题