如何从有序字典列表中获取所需的值

时间:2017-08-08 01:35:33

标签: python python-2.7

我有一个有序词典列表。我想获取25G的端口值,其中端口6/2位于100G

>>> from collections import OrderedDict
>>> a = [OrderedDict([('name', 601), ('100G', '6/1'), ('25G', ['6/5', '6/6', '6/7', '6/8']), ('init', '100G'), ('current', '100G')]), OrderedDict([('name', 602), ('100G', '6/2'), ('25G', ['6/9', '6/10', '6/11', '6/12']), ('init', '100G'), ('current', '100G')])]
>>> a['name']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

# something like this
if a['100G'] == '6/2':
    b = a['25G']
# required output is
['6/9', '6/10', '6/11', '6/12']

我尝试将此列表转换为字典,但无法执行此操作,name我也无法访问它,有人可以帮助我访问所需的值吗?

1 个答案:

答案 0 :(得分:0)

只需遍历列表:

>>> for x in a:
...     if x['100G'] == '6/2':
...         print x['25G']
... 
['6/9', '6/10', '6/11', '6/12']

或者,因为您询问了列表理解:

>>> [x['25G'] for x in a if x['100G'] == '6/2']
[['6/9', '6/10', '6/11', '6/12']]