首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从有序字典列表中获取所需的值

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

Stack Overflow用户
提问于 2017-08-08 09:35:33
回答 1查看 31关注 0票数 0

我有一份有序字典的清单。我想获取25G的端口值,其中端口6/2100G中。

代码语言:javascript
复制
>>> 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我也不能访问它,有人能帮我访问所需的值吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-08 09:39:29

只需遍历列表:

代码语言:javascript
复制
>>> for x in a:
...     if x['100G'] == '6/2':
...         print x['25G']
... 
['6/9', '6/10', '6/11', '6/12']

或者,既然你问的是列表理解:

代码语言:javascript
复制
>>> [x['25G'] for x in a if x['100G'] == '6/2']
[['6/9', '6/10', '6/11', '6/12']]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45557996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档