Accessing items in an collections.OrderedDict by index

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

    If you're dealing with fixed number of keys that you know in advance, use Python's inbuilt namedtuples instead. A possible use-case is when you want to store some constant data and access it throughout the program by both indexing and specifying keys.

    import collections
    ordered_keys = ['foo', 'bar']
    D = collections.namedtuple('D', ordered_keys)
    d = D(foo='python', bar='spam')
    

    Access by indexing:

    d[0] # result: python
    d[1] # result: spam
    

    Access by specifying keys:

    d.foo # result: python
    d.bar # result: spam
    

    Or better:

    getattr(d, 'foo') # result: python
    getattr(d, 'bar') # result: spam
    

提交回复
热议问题